[英]Content-Disposition: download file automatically
The API call to the server is returning a zip file with Content-Disposition
in format attachment, <filename>
I am using FileSaver's saveAs to save the file.对服务器的 API 调用返回一个 zip 文件,格式附件为Content-Disposition
attachment, <filename>
我正在使用 FileSaver 的 saveAs 保存文件。
this.ajax.raw(requestUrl, {
dataType: 'binary',
xhr: () => {
const myXhr = $.ajaxSettings.xhr()
myXhr.responseType = 'blob'
return myXhr
}
}).then((response) => {
this.downloadSuccess(response, minTimeString, maxTimeString, downloadCompletedMessage)
}).catch((e) => {
this.downloadError(e)
})
downloadSuccess (response, minTime, maxTime, downloadCompletedMessage) {
const filename = (response.jqXHR.getResponseHeader('Content-Disposition').split('"')[1])
saveAs(response.payload, filename, 'application/zip')
This works fine for small files but fails if the file is more than 2Gb (The file is downloaded successfully but the saved file is of 1Kb only).这适用于小文件,但如果文件超过 2Gb(文件下载成功但保存的文件仅为 1Kb)则失败。
During my research, I saw that browser can download the file without FileSaver if the response has Content-Disposition
which is true in my case.在我的研究过程中,我发现如果响应具有Content-Disposition
,浏览器可以在没有 FileSaver 的情况下下载文件,这在我的例子中是正确的。 But I am not able to figure out how.但我无法弄清楚如何。
Do I need to use request differently?我需要以不同的方式使用请求吗?
Content-Disposition attachment header is the best preferred way to download files from the browser. Content-Disposition 附件 header 是从浏览器下载文件的最佳首选方式。 It has better cross browser compatibility, won't have any memory limit and it doesn't require any JavaScript.它具有更好的跨浏览器兼容性,不会有任何 memory 限制,也不需要任何 JavaScript。
You don't need ajax request
to download the file.您不需要ajax request
来下载文件。 Only ensure that server add Content-Disposition
header and provide a link to download.只需确保服务器添加Content-Disposition
header 并提供下载链接即可。
If you can also use the anchor download attribute from HTML5.如果您还可以使用来自 HTML5 的锚点下载属性。
Causes the browser to treat the linked URL as a download.使浏览器将链接的 URL 视为下载。
const link = document.createElement('a');
link.href = '/xyz/abc.pdf';
link.download = "file.pdf";
link.dispatchEvent(new MouseEvent('click'));
<a href="/xyz/abc.pdf" download="file.pdf"></a>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.