I am currently attempting to have the browser automatically prompt the user to save a file from server. I have a Java Servlet coded as follows:
private void doDownload( HttpServletRequest request, HttpServletResponse response){
File f = new File(<filename.ext> //This is text file but I have tried with pdfs, gifs, zips
ServletOutputStream op = response.getOutputStream();
int length = 0;
op = response.getOutputStream();
String mimetype = context.getMimeType( f.getAbsolutePath() );
resp.setContentType("application/x-download");
response.setContentLength( (int)f.length() );
response.setHeader("Content-disposition", "attachment; filename=<newFileName.ext>");
byte[] bbuf = new byte[8192];
DataInputStream in = new DataInputStream(new FileInputStream(f));
while ((in != null) && ((length = in.read(bbuf)) != -1))
{
op.write(bbuf,0,length);
}
in.close();
op.flush();
op.close();
}
I am using Firefox to do the testing and I have Firebug running. I can see the Firebug response contains the headers as I have set them and that when the request is for a text file, all the text that should be there is contained in the response.
On the client I have Javascript making the request asynchronously as follows:
try{
xmlhttp = window.XMLHttpRequest?new XMLHttpRequest(): new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
}
xmlhttp.open("post", 'myUrl?action=download', true);
xmlhttp.send(null);
I can see that the request makes contact with the server and that the response is correct, as I said above that I can see the text file etc. in the Firebug response output.
The problem is that nothing happens from here, there is simply no browser response. I have scoured the internet for the correct way to do this but all that I can find is that the server needs to set the content-disposition to “attachment; filename=” and that the contentType should be set to “application/x-download”. I have tried setting the contentType to “application/octet-stream” but nothing that I have tried seems to work.
Please can someone explain to me if there is something that I am doing wrong?
You have to make the browser “visit” the page for the download dialog to appear. Just sending a post request is not enough.
Probably the best way to do this with JavaScript is to dynamically make a
<form>object withaction="/your/servlet/page"and then use JavaScript to callsubmit()on the form object (don’t forget to add the<form>to the page or it won’t work).