将文件从 expressJS (sendFile) 服务器下载到 VueJS,是否返回损坏的文件?

Esn*_*aky 3 blob node.js express vue.js vuejs2

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

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

我的快速路由实际上使用 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();
      })
Run Code Online (Sandbox Code Playgroud)

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

Esn*_*aky 5

感谢@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();
      })
Run Code Online (Sandbox Code Playgroud)