简体   繁体   English

从servlet Java下载zip

[英]Download a zip from a servlet Java

I don't understand why this is so hard and everybody has it's own implementation... 我不明白为什么这么难,每个人都有自己的实施......

So in my server, I generate a .zip file which I want the user to be able to download upon click. 所以在我的服务器中,我生成一个.zip文件,我希望用户能够在点击时下载。

So I set up the request, which the server successfully receives and now, i'm struggling with writing the byte array to the output. 所以我设置了服务器成功接收的请求,现在,我正在努力将字节数组写入输出。

Here's my code for the response: 这是我的响应代码:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        System.out.println("Downloading clusters.zip");

        /* Generate the directory on the server, then zip it. */
        clustersToFiles();
        zipClusters();
        /* Now the zip is saved on zipFullPath */

        System.out.println("Done generating the .zip");

        String parent_dir = System.getProperty("catalina.base");
        String filename = "clusters.zip";
        String zipFullPath = parent_dir + "/" + filename;

        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
        OutputStream out = response.getOutputStream();

        FileInputStream fis = new FileInputStream(zipFullPath);
        int bytes;
        while ((bytes = fis.read()) != -1) {
            System.out.println(bytes);
            out.write(bytes);
        }
        fis.close();
        response.flushBuffer();

        System.out.println(".zip file downloaded at client successfully");
}

The fact that the downloaded file is a ZIP isn't relevant (except for the content type), you just want to download a binary file. 下载的文件是ZIP的事实是不相关的(内容类型除外),您只想下载二进制文件。

PrintWriter isn't good at that, this writer is used to write text output, and the write(int) method you are using : PrintWriter并不擅长这个,这个编写器用于编写文本输出,以及您正在使用的write(int)方法:

Writes a single character . 写一个字符

Just use a low level plain OutputStream , its write(int) method : 只需使用低级普通OutputStream ,其write(int)方法:

Writes the specified byte to this output stream. 将指定的字节写入此输出流。

So just go : 所以,去吧:

OutputStream out = response.getOutputStream();

You may find some more ways of doing it in this question : Implementing a simple file download servlet 您可以在此问题中找到更多方法: 实现简单的文件下载servlet

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM