shortspider shortspider - 9 months ago 42
Java Question

Save file dialog not appearing

I am tryig to make a song available for download on my website. I am using a download servlet that I have used before to make zip files available for download. I have run through the code and everything appears to be working, the output stream reads the entire file but the save dialog box does not appear. Any ideas? Thanks for your help. Code is as follows:

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String song = request.getParameter("song");
StringBuilder filePath = new StringBuilder();
try {
String[] info = getSongInfo(song);
filePath.append("D:\\My Music\\My Song.m4a");
File file = new File(filePath.toString());
if (!file.exists()) {
throw new FileNotFoundException(file.getAbsolutePath());
response.setHeader("Content-Length", String.valueOf(file.length()));
response.setHeader("Content-Type", "audio/mp4a-latm");
response.setHeader("Content-disposition", "attachment; filename="+song+".m4a");
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
byte[] buf = new byte[4096];
while (true) {
int length =;
if (length == -1) {
bos.write(buf, 0, length);
} catch (InterruptedException e) {
System.err.println("Error message: " + e.getMessage());

Called using:

url: "/downloadSong?song="+item.title[0]


You cannot download files by ajax. JavaScript has due to security reasons no facility to spawn a Save As dialogue nor to store them in disk. It will consume the response, but it can't do anything sensible with it.

You need to use window.location instead:

window.location = "/downloadSong?song=" + item.title[0];

Thanks to the Content-Disposition: attachment header, it won't affect the currently opened page.