从servlet Java

时间:2017-04-05 13:37:40

标签: java servlets

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

所以在我的服务器中,我生成一个.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");
}

1 个答案:

答案 0 :(得分:4)

下载的文件是ZIP无关紧要(内容类型除外),您只想下载二进制文件。

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

  

写一个字符

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

  

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

所以就去:

OutputStream out = response.getOutputStream();

您可以在此问题中找到更多方法:Implementing a simple file download servlet