2019 modern browsers update
(2019现代浏览器更新)
This is the approach I'd now recommend with a few caveats:
(这是我现在建议的一些注意事项:)
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!'));
2012 Original jQuery/iframe/Cookie based approach
(2012年基于jQuery / iframe / Cookie的原始方法)
Bluish is completely right about this, you can't do it through Ajax because JavaScript cannot save files directly to a user's computer (out of security concerns).
(Bluish完全是正确的,您无法通过Ajax做到这一点,因为JavaScript无法将文件直接保存到用户的计算机(出于安全考虑)。)
Unfortunately pointing the main window's URL at your file download means you have little control over what the user experience is when a file download occurs. (不幸的是,将主窗口的 URL指向文件下载意味着您??几乎无法控制文件下载发生时的用户体验。)
I created jQuery File Download which allows for an "Ajax like" experience with file downloads complete with OnSuccess and OnFailure callbacks to provide for a better user experience.
(我创建了jQuery File Download ,它允许通过OnSuccess和OnFailure回调完成文件下载 ,从而获得“类似于Ajax”的体验,以提供更好的用户体验。)
Take a look at my blog post on the common problem that the plugin solves and some ways to use it and also a demo of jQuery File Download in action . (看看我的博客文章 ,了解该插件解决的常见问题以及使用该插件的一些方法,以及运行中的jQuery File演示 。)
Here is the source (这是来源)
Here is a simple use case demo using the plugin source with promises.
(这是一个使用带有Promise的插件源的简单用例演示。)
The demo page includes many other, 'better UX' examples as well. (演示页面还包括许多其他“更好的UX”示例。)
$.fileDownload('some/file.pdf')
.done(function () { alert('File download a success!'); })
.fail(function () { alert('File download failed!'); });
Depending on what browsers you need to support you may be able to use https://github.com/eligrey/FileSaver.js/ which allows more explicit control than the IFRAME method jQuery File Download uses.
(根据您需要支持的浏览器,您可能可以使用https://github.com/eligrey/FileSaver.js/ ,它比jQuery File Download使用的IFRAME方法提供更明确的控制。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…