我正在使用 vuejs 2 + axios。我需要发送一个获取请求,将一些参数传递给服务器,并获取一个 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
})
原文由 Victor 发布,翻译遵循 CC BY-SA 4.0 许可协议
你得到的是空的 PDF,因为没有数据传递到服务器。您可以尝试使用这样的数据对象传递数据
顺便说一句,我非常感谢你向我展示了提示,以便从回复中下载 pdf。谢谢你:)
我使用的方式是,