使用Axios从http响应下载PDF

问题描述 投票:2回答:2

我正在使用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));
},
javascript http vue.js axios
2个回答
2
投票

正如@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));
},

0
投票

你有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代码,你会发现相同的实现。

© www.soinside.com 2019 - 2024. All rights reserved.