我正在尝试将 pdf 文件从节点服务器下载到 React 客户端,但是当我打开它时,它显示为空白

Raj*_*r J 4 html javascript node.js reactjs axios

我只是从节点的文件中读取数据并将内容类型发送为“应用程序/pdf”。

我的节点版本是 10。

服务器端.js:

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

客户端.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();
      })
Run Code Online (Sandbox Code Playgroud)

pdf 正在下载,但什么也没显示,当我用 Vs Code 打开它时,它向我显示了这样的内容:

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

tar*_*ugh 8

只需添加responseType为带有 value 的标题arraybuffer。你应该很高兴去。

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

希望有帮助!!!