![](/img/trans.png)
[英]Content-Disposition headers to allow both download and open file
[英]Content-Disposition: download file automatically
對服務器的 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')
這適用於小文件,但如果文件超過 2Gb(文件下載成功但保存的文件僅為 1Kb)則失敗。
在我的研究過程中,我發現如果響應具有Content-Disposition
,瀏覽器可以在沒有 FileSaver 的情況下下載文件,這在我的例子中是正確的。 但我無法弄清楚如何。
我需要以不同的方式使用請求嗎?
來自文檔:
Content-Disposition 附件 header 是從瀏覽器下載文件的最佳首選方式。 它具有更好的跨瀏覽器兼容性,不會有任何 memory 限制,也不需要任何 JavaScript。
您不需要ajax request
來下載文件。 只需確保服務器添加Content-Disposition
header 並提供下載鏈接即可。
如果您還可以使用來自 HTML5 的錨點下載屬性。
使瀏覽器將鏈接的 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.