繁体   English   中英

从servlet Java下载zip

[英]Download a zip from a servlet Java

我不明白为什么这么难,每个人都有自己的实施......

所以在我的服务器中,我生成一个.zip文件,我希望用户能够在点击时下载。

所以我设置了服务器成功接收的请求,现在,我正在努力将字节数组写入输出。

这是我的响应代码:

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");
}

下载的文件是ZIP的事实是不相关的(内容类型除外),您只想下载二进制文件。

PrintWriter并不擅长这个,这个编写器用于编写文本输出,以及您正在使用的write(int)方法:

写一个字符

只需使用低级普通OutputStream ,其write(int)方法:

将指定的字节写入此输出流。

所以,去吧:

OutputStream out = response.getOutputStream();

您可以在此问题中找到更多方法: 实现简单的文件下载servlet

暂无
暂无

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

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