从servlet下载生成的zip文件
问题描述:
我知道这是一个非常基本的问题,但有很多实现,我无法让它们工作。从servlet下载生成的zip文件
所以在我的项目中,如果用户点击一个按钮,我在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>
这里的AJAX
为POST
:
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
。但下载无法启动。这里有什么可能是错误的?
答
,如果你正确地发送您的Ajax调用后,你应该只简单地处理它的响应,这样的:
$.ajax({
url:'GetZipServlet',
type:'GET',
success: function (response) {
//handle the response here
}
});
谢谢您的答复。它没有工作 – Mixalis