从请求响应创建 PDF 不适用于 axios,但适用于本机 xhr [英] Creating PDF from request response doesn't work with axios but works in native xhr
问题描述
为了强制从服务器下载 PDF,我尝试使用 axios 和本机 xhr 对象.原因是我必须发送 post 请求,因为我向服务器传递了太多数据,所以带有简单链接的选项(如 site.ru/download-pdf
对我不起作用).
In order to force download PDF from server I tried to use axios and native xhr object. The reason is that I have to send post request, because I pass too much data to server, so the option with simple link (like site.ru/download-pdf
won't work for me).
即使我最终设法用 Xhr 做到了这一点,我仍然不知道为什么 axios 方式不起作用.
Even though I finally managed to do this with Xhr, I still don't have a clue why axios way doesn't work.
这是我使用 xhr 执行此操作的方法,它对我有用:
Here is how I do this with xhr and it works for me:
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,但它们都是空的:
Here is "axios-way" and I actually get PDF with correct number of pages, but they are all empty:
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 中,否则我无法在服务器端获取数据.
Axios is already configured to send Authorization token.
I put Application/x-www-form-urlencoded
in xhr because otherwise I couldn't get data in server side.
即使 xhr 有效,我还是更喜欢使用 axios,因为我在任何地方都使用它,而且我只是好奇我做错了什么.我尝试了不同的解决方案,但只有原生 xhr 可以完成这项工作.
Even though xhr works, I'd prefer to use axios since I use it everywhere and I'm just curios what I'm doing wrong. I tried different solutions, and only native xhr did the job.
推荐答案
以下对我有用:
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));
如果这有帮助,请告诉我.
Let me know if this helps.
干杯!
这篇关于从请求响应创建 PDF 不适用于 axios,但适用于本机 xhr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!