gpt4 book ai didi

javascript - 使用 Axios 从 http 响应下载 PDF

转载 作者:搜寻专家 更新时间:2023-10-30 22:15:19 25 4
gpt4 key购买 nike

我正在开发一个带有 Laravel 后端 API 的 Vue 应用程序。单击链接后,我想调用服务器以下载某个文件(大部分时间是 PDF 文件)。当我使用 axios 执行 get 请求时,我在响应正文中得到一个 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));
},

关于javascript - 使用 Axios 从 http 响应下载 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51514391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com