为了强制从服务器下载PDF,我尝试使用axios和本机xhr对象.原因是我必须发送post请求,因为我向服务器传递了太多数据,所以带有简单链接的选项(如site.ru/download-pdf对我来说不起作用).
即使我最终设法用Xhr做到这一点,我仍然不知道为什么axios方法不起作用.
let xhr = new XMLHttpRequest()
xhr.open('POST', Vue.config.baseUrl + `order-results/${id}/export-pdf`, true)
xhr.setRequestHeader("Authorization", 'Bearer ' + this.token())
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xhr.responseType = 'arraybuffer'
xhr.onload = function(e) {
if (this.status === 200) {
let blob = new Blob([this.response], { type:"application/pdf" })
let link = document.createElement('a')
link.href = window.URL.createObjectURL(blob)
link.download = 'Results.pdf'
link.click()
}
};
xhr.send("data=" + data);
这是“axios-way”,我实际上得到了具有正确页数的PDF,但它们都是空的:
axios.post(`order-results/${id}/export-pdf`, {
data,
responseType: 'arraybuffer'
}).then((response) => {
let blob = new Blob([response.data], { type:"application/pdf" })
let link = document.createElement('a')
link.href = window.URL.createObjectURL(blob)
link.download = 'Results.pdf'
link.click()
})
Axios已配置为发送授权令牌.
我把Application / x-www-form-urlencoded放在xhr中,否则我无法在服务器端获取数据.
即使xhr工作,我更喜欢使用axios,因为我到处使用它而且我只是好奇我做错了什么.我尝试了不同的解决方案,只有本地xhr才能完成这项工作.
解决方法:
以下适用于我:
axios.post("http://localhost:8080/reports/my-report/",
data,
{
responseType: 'arraybuffer',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/pdf'
}
})
.then((response) => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'file.pdf'); //or any other extension
document.body.appendChild(link);
link.click();
})
.catch((error) => console.log(error));
如果这有帮助,请告诉我.
干杯!