【问题标题】:Download docx as blob将 docx 下载为 blob
【发布时间】:2016-12-16 22:12:27
【问题描述】:

我用快递从后端发送一个 docx:

module.exports = (req, res) => {
  res.status(200).sendFile(__dirname+"/output.docx")
}

我调用它并将它作为一个 blob 从 angular 下载:

 $http({
   url: '/api_cv/cv/gen',
   method: "PUT",
   responseType: 'blob'
}).success(function (data, status, headers, config) {
   var blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
   var fileName = headers('content-disposition');
   saveAs(blob, 'file.docx');
}).error(function (data, status, headers, config) {
    console.log('Unable to download the file')
});

它适用于 Chrome 和 firefox。在 safari 中会打开一个新选项卡,但不会下载任何文件。在 IE 中(通过 Azure RemoteApp 测试,因为我有一个 mac),我得到“你当前的安全设置不允许下载这个文件”。

SaveAs is from https://github.com/eligrey/FileSaver.js/

是否有一种替代方法可以在所有现代浏览器和 IE10+ 中使用?

【问题讨论】:

  • 您是否尝试过使用arraybuffer 而不是blob 作为responseType?还可能想检查您是否可以访问标题,我知道有时您必须明确允许使用 Access-Control-Expose-Headers 访问
  • 试过了。结果相同。
  • 嗯...出于兴趣,saveAs 函数有什么作用?我昨天做了一些非常相似的事情,将 xlsx 保存为 blob 并且它运行良好,尽管在 Chrome 中。
  • 它保存文件。 github.com/eligrey/FileSaver.js
  • 对了,不知道是不是你自己写的。

标签: javascript angularjs express


【解决方案1】:

不使用saveAs,您可以尝试以下方法:

var url = window.URL || window.webkitURL;
var downloadUrl = url.createObjectURL(blob);

var a = doc.createElement("a");
a.style.display = "none";

if (typeof a.download === "undefined") {
   window.location = downloadUrl;
} else {
   a.href = downloadUrl;
   a.download = fileName;
   doc.body.appendChild(a);
   a.click();
}

然后在完成后移除锚点。只是想知道是否是保存部分的问题,我对 FileSaver 没有太多经验,但这是我过去所做的

【讨论】:

  • 这正是 FileSaver 内部剂量 - 与其他后备解决方案说,例如具有 navigator.saveOrOpenBlob() 的 IE10
猜你喜欢
  • 2022-01-22
  • 1970-01-01
  • 2022-01-02
  • 1970-01-01
  • 1970-01-01
  • 2019-03-01
  • 1970-01-01
  • 2014-09-24
  • 1970-01-01
相关资源
最近更新 更多