繁体   English   中英

Content-Disposition:自动下载文件

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM