使用Axios从http响应下载PDF

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用Axios从http响应下载PDF相关的知识,希望对你有一定的参考价值。

我正在使用Laravel后端API处理Vue应用程序。点击链接后,我想打电话给服务器下载某个文件(大部分时间是PDF文件)。当我用getaxios请求时,我得到了一个PDF作为回复,在回复的正文中。我想直接下载该文件。

为了让您更好地了解响应的外观:

enter image description here(注意:我知道真正的文本响应比图像更好,但由于实际PDF内容的长度,我没有看到任何返回的方法..)

有没有办法用javascript或其他东西下载该文件?必须具体直接下载,而无需再次单击该按钮。

// This method gets called when clicking on a link
downloadFile(id) {
    const specificationId = this.$route.params.specificationId;

    axios
        .get(`${this.$API_URL}/api/v1/suppliersmanagement/product-specifications/${specificationId}/fileupload/${id}/download`, {
            headers: this.headers,
        })
        .then(response => {
            console.log(response);
            // Direct download the file here..
        })
        .catch(error => console.log(error));
},
答案

正如@Sandip Nirmal建议我使用downloadjs并且效果非常好!不得不对我的代码进行一些调整,但最终还是解决了。

我的新代码

// npm i downloadjs
import download from 'downloadjs'

// method
downloadFile(file) {
    const specificationId = this.$route.params.specificationId;

    axios
        .get(`${this.$API_URL}/api/v1/suppliersmanagement/product-specifications/${specificationId}/fileupload/${file.id}/download`, {
            headers: this.headers,
            responseType: 'blob', // had to add this one here
        })
        .then(response => {
           const content = response.headers['content-type'];
           download(response.data, file.file_name, content)
        })
        .catch(error => console.log(error));
},
另一答案

你有2个选择。如果您想从服务器执行此操作,并且您使用Node.js作为后端。您可以使用res.download快速方法轻松完成。你可以按照这个Download a file from NodeJS Server using Express的答案。

但是如果你想从客户端处理它,那么几乎没有选择,因为你不能直接使用axios,XHR,fetch来下载文件。您可以使用download.js或以下列方式编写自己的代码。

return axios({
    url: '/download', // download url
    method: 'get'
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
      mode: 'no-cors'
    }
  })
    .then(response => response.blob())
    .then(blob => {
      var url = window.URL.createObjectURL(blob)
      var a = document.createElement('a')
      a.href = url
      a.download = fileName
      a.click()
      a.remove()
      setTimeout(() => window.URL.revokeObjectURL(url), 100)
    })

由于从服务器返回的响应是json格式,您需要将其转换为ObjectURL并将其设置为锚标记。

如果你潜入download.js代码,你会发现相同的实现。

以上是关于使用Axios从http响应下载PDF的主要内容,如果未能解决你的问题,请参考以下文章

从请求响应创建 PDF 不适用于 axios,但适用于本机 xhr

无法通过 Vue.js(Axios 帖子)从 Laravel 后端下载文件(pdf)

axios 和 reactjs:预检响应具有无效的 HTTP 状态代码 400

使用javascript下载时PDF为空白

使用javascript下载时PDF为空白

Axios介绍和使用