【问题标题】:Downloading files from expressJS (sendFile) server to VueJS, is returning corrupted files?从 expressJS (sendFile) 服务器下载文件到 VueJS,是否返回损坏的文件?
【发布时间】:2019-01-19 11:24:56
【问题描述】:

我有一个用 expressjs 编写的 API,它在提供文件 ID 时发送一个文件。

后端工作正常,因为当直接在浏览器中输入路由 url 时,它会发送正确的文件(未损坏)。 前任。 http://localhost:8080/download?id=1234 (下载所有文件就好了 ie.txt, xlsx, jpg, zip)

我的 express 路由实际上使用 res.download,它实际上只是 sendFile 的包装器。

当我尝试从 Vue http get 请求中调用这些路由 url 时,它只返回未损坏的 txt 文件。所有其他文件下载,但由于损坏,它们可以打开。

谁能指出我正确的方向,为什么它不能在 Vue 中工作?

为清楚起见,“item”作为参数传递给此函数。

        this.$http.get("http://localhost:8000/files/download", {params:{id:item._id}}, {responseType: 'arraybuffer'})
      .then(response => {

        var blob = new Blob([response.data], {type:response.headers.get('content-type')});

        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = item.filename;
        link.click();
      })

供参考,这是我的特快路线

【问题讨论】:

  • 尝试将 responseType 更改为 blob
  • 还有new Blob([response.data], { type: "text/plain" })。看看这是否有效
  • @Helpinghand 感谢您的建议!不幸的是,它仍然返回损坏的 jpg、zip 和 xlsx 文件。当它变成一团乱七八糟的东西时,它一定是什么东西。
  • 我考虑将每个文件的 src 属性绑定到“计算”字符串,因为直接在浏览器中输入路由可以正确下载它们。但是,一旦我稍后实施身份验证(并删除对所有人开放的 cors),我觉得这还不够。
  • 是的,一旦添加了身份验证就不会好了。我找到了这个,type: 'application/pdf'stackoverflow.com/questions/50736657/…

标签: node.js express vue.js vuejs2 blob


【解决方案1】:

感谢@Helpinghand 帮助我解决此问题。

“我在您发布的链接中找到了解决方案。问题是我在分配“内容类型”之前明确地在其自己的对象中发送参数。您发布的示例将查询参数连接到 url。之后开关,它工作完美”。

this.$http.get(`http://localhost:8000/files/download?id=${item._id}`, {responseType: 'arraybuffer'})
      .then(response => {
        console.log(response.headers.get('content-type'));
        console.log(response);

        var blob = new Blob([response.body], {type:response.headers.get('content-type')});

        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = item.filename_version;
        link.click();
      })

【讨论】:

  • 我认为 [response.body] 应该是 [response.data],至少这对我有用!
  • responseType arraybuffer 是这里的关键。 axios 需要 res.data
猜你喜欢
  • 2016-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-18
  • 1970-01-01
  • 1970-01-01
  • 2019-12-12
  • 2020-11-10
相关资源
最近更新 更多