Force download GET request using axios
You're getting empty PDF 'cause no data is passed to the server. You can try passing data using data object like this
axios .post(`order-results/${id}/export-pdf`, { data: { firstName: 'Fred' }, 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 })
By the way I gotta thank you so much for showing me the hint in order to download pdf from response. Thank ya :)
var dates = { fromDate: 20/5/2017, toDate: 25/5/2017 }
The way in which I have used is,
axios({ method: 'post', url: '/reports/interval-dates', responseType: 'arraybuffer', data: dates}).then(function(response) { let blob = new Blob([response.data], { type: 'application/pdf' }) let link = document.createElement('a') link.href = window.URL.createObjectURL(blob) link.download = 'Report.pdf' link.click()})
Try this:It works perfectly for me with compatibility for Internet Explorer 11 (createObjectURL doesn't work on Explorer 11)
axios({ url: 'http://vvv.dev', method: 'GET', responseType: 'blob', // important}).then((response) => { if (!window.navigator.msSaveOrOpenBlob){ // BLOB NAVIGATOR const url = window.URL.createObjectURL(new Blob([response.data])); const link = document.createElement('a'); link.href = url; link.setAttribute('download', 'download.pdf'); document.body.appendChild(link); link.click(); }else{ // BLOB FOR EXPLORER 11 const url = window.navigator.msSaveOrOpenBlob(new Blob([response.data]),"download.pdf"); }});
https://gist.github.com/javilobo8/097c30a233786be52070986d8cdb1743
I don't think its possible to do this in axios or even AJAX. The file will be kept in memory, i.e. you cannot save file to disk. This is because JavaScript cannot interact with disk. That would be a serious security issue and it is blocked in all major browsers.
You can construct your URL in front-end and download it in the following way:
var url = 'http://example.com/order-results/' + id + '/export-pdf?' + '..params..' window.open(url, '_blank');
Hope this helps!