相关疑难解决方法(0)

使用axios强制下载GET请求

我正在使用vuejs 2 + axios.我需要发送一个get请求,将一些params传递给服务器,并获得一个PDF作为响应.服务器使用Laravel.

所以

axios.get(`order-results/${id}/export-pdf`, { params: { ... }})
Run Code Online (Sandbox Code Playgroud)

成功请求,但它不会启动强制下载,即使服务器返回正确的标头.

我认为这是一种典型情况,例如,您需要形成PDF报告并将一些过滤器传递给服务器.那怎么可能实现呢?

更新

所以实际上我找到了解决方案.然而同样的方法不适用于axios,不知道为什么,这就是我使用原始XHR对象的原因.所以解决方案是创建一个blob对象和用户createUrlObject函数.示例示例:

let xhr = new XMLHttpRequest()
xhr.open('POST', Vue.config.baseUrl + `order-results/${id}/export-pdf`, true)
xhr.setRequestHeader("Authorization", 'Bearer ' + this.token())
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xhr.responseType = 'arraybuffer'

xhr.onload = function(e) {
  if (this.status === 200) {
    let blob = new Blob([this.response], { type:"application/pdf" })
    let link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = 'Results.pdf'
    link.click()
  }
}
Run Code Online (Sandbox Code Playgroud)

重要提示:您应该将数组缓冲区作为响应类型

但是,在axios中编写的相同代码返回的PDF为空:

axios.post(`order-results/${id}/export-pdf`, {
  data,
  responseType: 'arraybuffer'
}).then((response) => {
  console.log(response)

  let blob …
Run Code Online (Sandbox Code Playgroud)

javascript vue.js axios vuejs2

31
推荐指数
4
解决办法
5万
查看次数

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

我有一个用 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)

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

blob node.js express vue.js vuejs2

3
推荐指数
1
解决办法
2032
查看次数

标签 统计

vue.js ×2

vuejs2 ×2

axios ×1

blob ×1

express ×1

javascript ×1

node.js ×1