使用 Axios 从 http 响应下载 PDF

新手上路,请多包涵

我正在开发一个带有 Laravel 后端 API 的 Vue 应用程序。单击链接后,我想调用服务器以下载某个文件(大多数情况下是 PDF 文件)。当我使用 — 执行 axios get 请求时,我会在响应正文中得到一个 PDF 作为回报。我想直接下载那个文件。

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

在此处输入图像描述 (注意:我知道真实的文本响应比图像更好,但由于实际 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));
},

原文由 Giesburts 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 763
1 个回答

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

原文由 Giesburts 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题