I am currently implementing a file download in a web application. I was struggling a little with the pop up blocker, the download needs to start immediately after the user interaction, so there cannot be a server round trip. Now I noticed, that Goolge Drive for example allows you to download folders. When you do that, their server first creates a compressed zip file, which takes some time.When the server finished, the download starts immediately without another user interaction.
Now I am wondering how this can be done?
I wrote a function to download a file via url. In your case, you must use ajax request to make a zip file on server then give back url and run below function to download:
function download(url, filename){
fetch(url)
.then(resp => resp.blob())
.then(blob => {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
console.log('your file has downloaded!');
})
.catch(() => console.log('Download failed!'));
}
Test codepen here: download file via url