1

I have a java servlet called DownloadFile and in the Get Method I have some code that gets a file from a database and downloads it when I navigate to the url

localhost:9080/myapp/DownloadFile 

But I dont want to send my user to this page to have to download the file, so in my javascript on the click of a button I have this

$scope.downloadTemplate = function(){
    console.log("download template called");
    $.get("DownloadTemplate", function(responseText) {   
        console.log(responseText)
    });
}

The function gets called, and the servlet gets called but the file does not download. Why? Here is relevant servlet code

bytes = templateSet.getBytes("FILE");
            fileName = templateSet.getString("TEMPLATE_FILE_NAME");

            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + fileName);

            ServletOutputStream out = response.getOutputStream();
            out.write(bytes);
            out.flush();
            out.close();

How can I download the file and keep the user on the page where the download button is?

Thanks

iqueqiorio
  • 1,149
  • 2
  • 35
  • 78
  • "Does not download" means its content is not printed in console by the `console.log(responseText)` command? Keep in mind you cannot download a file using AJAX, you need a regular request / page redirect for that. – Jiri Tousek Dec 07 '16 at 20:34
  • @JiriTousek I do see it printed in the console, but the file does not download to my file system. So what type of request do I need? Why can you not do it with ajax – iqueqiorio Dec 07 '16 at 20:39
  • Possible duplicates: http://stackoverflow.com/questions/33786773/using-window-openurl-self-opens-download-window-but-not-get-request/33786994, http://stackoverflow.com/questions/4545311/download-a-file-by-jquery-ajax, http://stackoverflow.com/questions/20830309/download-file-using-an-ajax-request – Jiri Tousek Dec 07 '16 at 20:51

1 Answers1

1

You cannot download a file using AJAX.

If you perform AJAX, you get the response in the provided callback. Your Javascript can use it any way it likes, but it won't trigger a download in browser.

Browser shows the download dialog when it sends a (full-page) request and receives a header indicating that the response contains a file instead of a website.

The usual way to do this if you don't want a direct link to the file is to have the Javascript redirect the whole tab to the URL of the file, something like window.location.href = 'http://example.com/myfile';.

Jiri Tousek
  • 12,211
  • 5
  • 29
  • 43