I am receiving a pdf file as api call response from a node.js backend.The file opens in browser window in an encoded format.I have tried to download but the downloaded file has error opening it (error: failed to load pdf document).I am told the response body is base64 encoded.
Is their any way the pdf can be open /downloaded correctly.I am using react.js and is new to it.
code snippet :
import FileDownload from 'js-file-download';
export function getTaxInvoice({token}){
const authString = `Bearer ${token}`;
return (dispatch) => {
return axios.get(`${MAIN_URL}/rental_invoice`,{
headers: {Authorization: authString, 'Accept': 'application/json','Content-Type': 'application/pdf'},
responseType: "arraybuffer",//I have tried with blob as well
encoding: null
})
.then((response)=>{
FileDownload(response, 'some.pdf');
const taxInvoiceUrl = window.URL.createObjectURL(new Blob([response.data]));
window.open(taxInvoiceUrl, "_blank");
console.log( response);
// dispatch(taxInvoiceLoadSuccess(taxInvoiceUrl));
// dispatch(onViewChanged("rental_invoice"));
})
.catch((error)=>{
dispatch(taxInvoiceLoadFailed());
})
}
}
response from api call: image snippet
Try changing
FileDownload(response, 'some.pdf');
to
FileDownload(response.data, 'some.pdf');
Here is an example of some code I have used in the past to do this:
function downloadURI (url, name) {
var link = document.createElement('a')
link.download = name
link.href = url
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}
export function download (url, type = 'application/pdf', name = 'example') {
get(url, (err, result) => {
if (err) return handleError(err)
const blob = new Blob([result.body], { type })
const downloadUrl = URL.createObjectURL(blob)
downloadURI(downloadUrl, name)
})
}
It will download the file and create an object url and automatically trigger opening the file by programatically clicking a link.
Finally solved the issue.(My senior dev helped me).Final code is below: install base64js and filedownload on npm .
export function getTaxInvoice({token}){
const authString = `Bearer ${token}`;
return (dispatch) => {
return axios.get(`${MAIN_URL}/rental_invoice`,{
headers: {Authorization: authString, 'Accept': 'application/pdf','Content-Type': 'application/pdf'}
})
.then((response)=>{
FileDownload(base64js.toByteArray(response.data), 'some.pdf');
const taxInvoiceUrl = window.URL.createObjectURL(new Blob([base64js.toByteArray(response.data)], { type: "application/pdf" }) );
window.open(taxInvoiceUrl, "_blank");
dispatch(taxInvoiceLoadSuccess(response.data));
dispatch(onViewChanged("rental_invoice"));
})
.catch((error)=>{
console.log(error);
dispatch(taxInvoiceLoadFailed());
})
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.