使用Axios从http响应下载PDF

时间:2018-07-25 08:36:11

标签: javascript http vue.js axios

我正在使用Laravel后端API开发Vue应用程序。单击链接后,我想调用服务器以下载特定文件(大多数情况下为PDF文件)。当我对get发出axios请求时,在响应的正文中得到了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));
},

3 个答案:

答案 0 :(得分: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));
},

答案 1 :(得分:0)

您有2个选择。如果要从服务器执行此操作,并且要使用Node.js作为后端。您可以使用res.download快速表达方法轻松地做到这一点。您可以针对该Download a file from NodeJS Server using Express遵循此答案。

但是,如果您想从客户端处理它,则几乎没有选择,因为您不能使用axios,XHR,提取直接下载文件。您可以使用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代码中,则会发现相同的实现。

答案 2 :(得分:-1)

您可以这样做

download(filename) {
  fetch(url , { headers })
  .then(response => response.blob())
  .then(blob => URL.createObjectURL(blob))
  .then(uril => {
    var link = document.createElement("a");
    link.href = uril;
    link.download = filename + ".csv";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  });
}

在这里我要下载CSV文件,因此我在文件名中添加了.csv。

相关问题