1

I have the following piece of code:

jQuery.ajax({
    type: "GET",
    url: "http://localhost:8081/myservicethatcontainsazipfile",      
    contentType:'application/zip',
    success: function (response) {
        console.log("Successful");
    },
    error: function (xhr, ajaxOptions, thrownError) {
        console.log("Error.");
    }
});

According to AJAX specifications, you can't download a file directly to the computer (security reasons), so I would like to know how can I download this file directly from the client without having to create and click an html element and similar options?

Pablo
  • 534
  • 11
  • 31
  • The browser will automatically download the file (and close the window after the download starts) if you tell the client's browser to go to that page: `window.open('http://localhost:8081/myservicethatcontainsazipfile')` – Adam Jenkins Jan 17 '17 at 14:59

2 Answers2

0

You cannot do it with AJAX. But, you can redirect / open a new window that takes the user to the file page, which will automatically start the download.

If you want no button you can use one of these lines of JavaScript.

window.open(download_url, '_blank')

window.location = 'download_url'

Take in mind that for security reasons you will need to wait for at least 3-5 seconds before starting the download.

setTimeout(() => window.location = 'download_url', 5000);

You should also have a look at How to start automatic download of a file in Internet Explorer?

Community
  • 1
  • 1
zurfyx
  • 31,043
  • 20
  • 111
  • 145
  • Do I need to pass as a parameter an url or can I just store my zip and send it? – Pablo Jan 17 '17 at 14:57
  • @Pablo your only parameter is the URL that takes to the download page. If you can reach it without any JavaScript code then you are good to redirect to it – zurfyx Jan 17 '17 at 14:59
  • That is not working for me (manually it does), maybe something to do with a CORS extension? (chrome) – Pablo Jan 17 '17 at 15:12
  • @Pablo CORS have nothing to do since it's a redirect. Do you get any error, are you getting redirect to that other page? You can even try with `window.location = 'https://www.google.com'` to make sure that line of code is being called. – zurfyx Jan 17 '17 at 15:18
0

You can also look at filesaver.js

https://github.com/eligrey/FileSaver.js/

snow_FFFFFF
  • 3,235
  • 17
  • 29