I know this is a very basic question but there are so many implementations out there and I can't get them to work.
So in my project if the user clicks a button, I'm generating a zip file on a servlet (which is called through an AJAX POST
). Naturally, I want that file to get downloaded to the user.
Here's my code for the request:
<button type="button" class="btn btn-info btn-lg" onclick="getZip();">
<span class="glyphicon glyphicon-download"></span> Download clusters (.zip)
</button>
Here's the AJAX
for the POST
:
function getzip() {
$.ajax({
url:'GetZipServlet',
type:'GET',
});
}
And this is my code for the download:
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");
}
I get the correct messages in my console, up to the .zip file downloaded at client successfully
. But the download doesn't start. what could be wrong here???
if you are correctly sending the response you should just simply handle it after your ajax call, like this:
$.ajax({
url:'GetZipServlet',
type:'GET',
success: function (response) {
//handle the response here
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.