I am currently utilizing Vue.js 2 with Axios to send a GET request and pass parameters to the server in order to retrieve a PDF as a response. The server is powered by Laravel.
Having issues with force downloading the PDF even though the correct headers are being returned from the server.
This scenario is common when generating a PDF report and sending filters to the server. How can this be achieved effectively?
Update
I have found a solution that works using raw XHR object instead of Axios. By creating a blob object and utilizing the `createUrlObject` function, I was able to successfully download the PDF file. Here's a sample example:
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()
}
}
Important: ensure that the responseType is set to array buffer
However, when attempting the same code with Axios, the returned PDF file is empty:
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);
})