Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I'm trying to download a pdf file from a node server to a react client but when I open it, it shows blank

I'm just reading the data from the file from node and sending the content type as "application/pdf".

My node version is 10.

serverside.js:

var file = path.join(__dirname,'Rajesh.pdf');
fs.readFile(file, function(err, data){
    res.contentType("application/pdf");
    res.send(data)
})

clientside.js:

axios.get('/api/downloadcv')
      .then(res => {
        const url = window.URL.createObjectURL(new Blob([res.data]
          ,{type: "application/pdf"}))
        var link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', 'resume.pdf');
        document.body.appendChild(link);
        link.click();
      })

The pdf is getting downloaded but it shows nothing, when I opened it with Vs Code it showed me something like this:

%PDF-1.4 %äüöß 2 0 obj <</Length 3 0 R/Filter/FlateDecode>> stream x��\K�d�m������n�u�F���Ad�d

like image 395
Rajesh Kumar J Avatar asked May 18 '19 07:05

Rajesh Kumar J


Video Answer


1 Answers

Just add responseType as header with value arraybuffer. You should be good to go.

axios.get('/api/downloadcv', {responseType: 'arraybuffer'})

Hope that helps!!!

like image 97
tarzen chugh Avatar answered Sep 19 '22 03:09

tarzen chugh