最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin4浏览0评论

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

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

Share Improve this question edited May 18, 2019 at 8:58 ProgrammerPer 1,1911 gold badge12 silver badges28 bronze badges asked May 18, 2019 at 7:33 Rajesh Kumar JRajesh Kumar J 2191 gold badge5 silver badges8 bronze badges 1
  • Why you putting the pdf contents on the dom? A simple open in new window or download attribute would do the same – Lawrence Cherone Commented May 18, 2019 at 11:30
Add a ment  | 

1 Answer 1

Reset to default 18

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

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

Hope that helps!!!

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论