繁体   English   中英

从servlet下载生成的zip

[英]Download generated zip from servlet

我知道这是一个非常基本的问题,但是有太多的实现方式,我无法让它们正常工作。

因此,在我的项目中,如果用户单击一个按钮,那么我将在servlet上生成一个zip文件(通过AJAX POST调用)。 自然,我希望将该文件下载到用户。

这是我的请求代码:

<button type="button" class="btn btn-info btn-lg" onclick="getZip();">
    <span class="glyphicon glyphicon-download"></span> Download clusters (.zip)
</button>

这是POSTAJAX

function getzip() {
    $.ajax({
        url:'GetZipServlet',
        type:'GET',
    });
}

这是我的下载代码:

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. */
        ClinicoGenomic.getInstance().clustersToFiles();
        ClinicoGenomic.getInstance().zipClusters();
        System.out.println("Done generating the .zip");

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



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

        ZipInputStream fi = new ZipInputStream(new FileInputStream(parent_dir + "/" + filename));
        int i;
        while ((i = fi.read())!=-1)
            zipStream.write(i);

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

我在控制台中收到正确的消息,直到.zip file downloaded at client successfully.zip file downloaded at client successfully 但是下载没有开始。 这里有什么问题吗???

如果您正确发送了响应,则只需在ajax调用之后简单地处理它,就像这样:

$.ajax({
  url:'GetZipServlet',
  type:'GET',
  success: function (response) {
     //handle the response here
  }
});

暂无
暂无

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

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