I am trying to send a pdf file hosted on the server to the client, to be downloaded from the browser. I am using express and node js.
The code on the server is :
app.get('/files', async (req, res) => {
res.sendFile(__dirname + '/boarding-pass.pdf');
});
The code on the client (react js) is :
const handleClick = async () => {
const response = await axios({
url: 'http://localhost:4000/files',
// url: '/static/boarding-pass.pdf',
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/pdf',
'Authorization': 'Basic d29vZG1hYzpXb29kbWFjOTI3IQ=='
},
responseType: 'arraybuffer',
//responseType: 'blob', // important
});
console.log('response', response);
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'bp.pdf');
document.body.appendChild(link);
link.click();
}
export default () => <div><Button onClick={() => handleClick()}>Download file</Button></div>
If I try to open the file on the server (I am on a Mac), the file is opened correctly and I see the content. However when I download the file from the browser, it gets someway corrupted or truncated, or it is missing something, because I can not open it, and I am getting the message that it is not a valid file, although I can see that the size of both files in the file system is the same, but if I inspect the binaries with an utility, I can see both files are different..
Can someone tell me what I am missing or provide an small working example?
Thank you
textin my answer with that value.