无法使用 Express 和 Node Js 打开从服务器下载的 pdf 文件

fgo*_*lez 1 javascript file download node.js express

我正在尝试将服务器上托管的 pdf 文件发送到客户端,以便从浏览器下载。我正在使用express和node js。

服务器上的代码是:

app.get('/files', async (req, res) => {
     res.sendFile(__dirname + '/boarding-pass.pdf');
    });
Run Code Online (Sandbox Code Playgroud)

客户端(react js)上的代码是:

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>
Run Code Online (Sandbox Code Playgroud)

如果我尝试在服务器上打开该文件(我在 Mac 上),该文件会正确打开并且我会看到内容。但是,当我从浏览器下载文件时,它会以某种方式损坏或截断,或者丢失某些内容,因为我无法打开它,并且我收到消息说它不是有效文件,尽管我可以看到文件系统中两个文件的大小相同,但是如果我使用实用程序检查二进制文件,我可以看到这两个文件是不同的。

有人可以告诉我我缺少什么或提供一个小的工作示例吗?

谢谢

c-c*_*vez 5

您可以尝试使用 Blob 的替代方法。

在链接的 href 中设置数据类型:

link.setAttribute('href', 'data:application/pdf;base64,' + text);
Run Code Online (Sandbox Code Playgroud)

或者

link.setAttribute('href', 'data:application/octet-stream;base64,' + text);
Run Code Online (Sandbox Code Playgroud)

或者,如果您仍然收到损坏的文件,请对您的内容进行编码:

link.setAttribute('href', 'data:application/pdf;charset=utf-8,' + encodeURIComponent(text));
Run Code Online (Sandbox Code Playgroud)

如果是文本我总是使用:

link.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
Run Code Online (Sandbox Code Playgroud)

下载文件后不要忘记删除 dom 对象:

document.body.removeChild(link);
Run Code Online (Sandbox Code Playgroud)

这是完整的代码:

let link= document.createElement('a');
link.setAttribute('href', ''data:application/pdf;base64,' + text);
link.setAttribute('download', 'bp.pdf');
document.body.appendChild(link);
link.click();
document.body.removeChild(link); // Remember to remove the dom object after downloading the file
Run Code Online (Sandbox Code Playgroud)

这是一个使用 Base64 编码的 pdf 显示此功能的小提琴:

小提琴