javascript 使用 Axios 从 http 响应下载 PDF
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51514391/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Download PDF from http response with Axios
提问by Giesburts
I am working on a Vue application with a Laravel back-end API. After clicking on a link I would like to do a call to the server to download a certain file (most of the time a PDF file). When I do a getrequest with axiosI get a PDF in return, in the body of the response. I would like to download that file directly.
我正在使用 Laravel 后端 API 开发 Vue 应用程序。单击链接后,我想调用服务器以下载某个文件(大部分时间是 PDF 文件)。当我get提出请求时,axios我会在响应正文中得到一个 PDF 作为回报。我想直接下载那个文件。
To give you a better view of how the response is looking like:
为了让您更好地了解响应的外观:
(note: I know a real text response is better than an image but I don't see any way to return that because of the length of the actual PDF content..)
(注意:我知道真实的文本响应比图像更好,但由于实际 PDF 内容的长度,我看不到任何返回它的方法..)
Is there any way of downloading that file with JavaScript or something? It has to be specific a direct download without clicking on the button again.
有没有办法用 JavaScript 或其他东西下载该文件?它必须是特定的直接下载,而无需再次单击该按钮。
Code
代码
// 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));
},
回答by Giesburts
As @Sandip Nirmal suggested I've used downloadjsand that worked out pretty good! Had to make a few adjustments to my code but in the end it worked out.
正如@Sandip Nirmal 建议的那样,我已经使用过downloadjs并且效果很好!不得不对我的代码进行一些调整,但最终还是成功了。
My new code
我的新代码
// 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));
},
回答by Sandip Nirmal
You have 2 options for this. If you want to do it from server and if you are using Node.js as a backend. You can do it easily using res.downloadmethod of express. You can follow this answer for that Download a file from NodeJS Server using Express.
为此,您有 2 个选择。如果您想从服务器执行此操作并且使用 Node.js 作为后端。您可以使用res.download快递的方法轻松完成。您可以按照此答案使用 Express 从 NodeJS 服务器下载文件。
But if you want to handle it from client then there are few options since you can't use axios, XHR, fetch to download file directly. You can either use download.jsor write your own code in following way.
但是如果您想从客户端处理它,那么由于您不能使用 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)
})
Since response returned from server is in jsonformat you need to convert it into ObjectURLand set it to anchor tag.
由于从服务器返回的响应是json格式,您需要将其转换为并将其ObjectURL设置为锚标记。
If you sneak inside download.jscode you will find same implementation.
如果你潜入download.js代码,你会发现相同的实现。
回答by VINEE
You can do it like this
你可以这样做
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);
});
}
here I want to download a CSV file, So I add .csv to the filename.
在这里我想下载一个 CSV 文件,所以我将 .csv 添加到文件名中。

