我正在使用vuejs 2 + axios。 我需要发送一个get请求,将一些参数传递给服务器,然后获取PDF作为响应。 服务器使用Laravel。
因此
axios.get(`order-results/${id}/export-pdf`, { params: { ... }})
成功发出请求,但不会启动强制下载,即使服务器返回正确的标头。
我认为这是一个典型的情况,当你需要生成PDF报告并将一些筛选器传递给服务器时。那么该如何实现呢?
更新
事实上,我找到了解决方案。然而,相同的方法在使用axios时无效,不知道为什么,所以我使用了原始的XHR对象。因此,解决方案是创建一个Blob对象并使用createUrlObject
函数。示例:
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()
}
}
重要提示:您应该将数组缓冲区设为响应类型
然而,使用axios编写的相同代码返回了空白PDF:
axios.post(`order-results/${id}/export-pdf`, {
data,
responseType: 'arraybuffer'
}).then((response) => {
console.log(response)
let blob = new Blob([response.data], { type: 'application/pdf' } ),
url = window.URL.createObjectURL(blob)
window.open(url); // Mostly the same, I was just experimenting with different approaches, tried link.click, iframe and other solutions
})
GET
方法,但最终使用了POST
方法。有什么特别的原因吗? - smchae