简体   繁体   中英

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

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

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

Hope that helps!!!

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM