简体   繁体   中英

Call to API REST and download the zip file to the computer

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?

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?

You can also look at filesaver.js

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM