This is the approach I'd now recommend with a few caveats:
A relatively modern browser is required
If the file is expected to be very large you should likely do something similar to the original approach (iframe and cookie) because some of the below operations could likely consume system memory at least as large as the file being downloaded and/or other interesting CPU side effects.
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(resp => resp.blob())
.then(blob => {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
// the filename you want
a.download = 'todo-1.json';
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
alert('your file has downloaded!'); // or you know, something with better UX...
})
.catch(() => alert('oh no!'));
jQuery File Download is a cross server platform compatible jQuery plugin that allows for an Ajax-like file download experience that isn't normally possible using the web.
Q: I need to send in custom headers. How do I do that?
Unfortunately since this plugin uses an iframe and not AJAX you cannot send in custom headers. If you really need to do this and are willing to accept a more narrow range of browser support this might be a better solution to your problem https://github.com/eligrey/FileSaver.js/
Q: It doesn't work!?
Try out the demo and make sure you are doing exactly what it is doing: http://jqueryfiledownload.apphb.com/ If the demo doesn't work in your browser you have defintely found a bug and us know!
Due to iframe security restrictions you must serve up the file from the same domain you see in the address bar
Supported and tested browsers
Internet Explorer 6+ - Works fine for standard use cases except in < IE9 JavaScript access to the failed response HTML doesn't (and can't) work reliably due to browser iframe constraints.
Firefox 11+ - reasonably sure it will work on earlier versions
Chrome 17+ - reasonably sure it will work on earlier versions
iOS 5.0+ - reasonably sure it will work on earlier versions
Android 4.0+ - non-GET requests do not work due to a long-standing bug in the Android browser. This is handled 'gracefully' with a message to the user.
Note - You must also write a cookie in conjunction with using this plugin in the server's response headers
请发表评论