我有一个Express服务器,可以创建PDF文件。
我正在尝试将此文件发送给客户端:
我正在尝试将此文件发送给客户端:
const fs = require('fs');
function download(req, res) {
var filePath = '/../../myPdf.pdf';
fs.readFile(__dirname + filePath, function(err, data) {
if (err) throw new Error(err);
console.log('yeyy, no errors :)');
if (!data) throw new Error('Expected data, but got', data);
console.log('got data', data);
res.contentType('application/pdf');
res.send(data);
});
}
在客户端,我想要下载它:
_handleDownloadAll = async () => {
console.log('handle download all');
const response = await request.get(
`http://localhost:3000/download?accessToken=${localStorage.getItem(
'accessToken'
)}`
);
console.log(response);
};
我收到一个类似于 body.text 的文本
%PDF-1.4↵1 0 obj↵<<↵/Title (��)↵/Creator (��)↵/Producer (��Qt 5.5.1)↵
但是我无法实现下载。
我该如何从数据中创建PDF或直接从服务器下载?
I've got it working: The answer was pretty simple. I just let the browser handle the download with an html anchor tag: server:
function download(req, res) {
const { creditor } = req.query;
const filePath = `/../../${creditor}.pdf`;
res.download(__dirname + filePath);
}
客户端:
<a href{`${BASE_URL}?accessToken=${accessToken}&creditor=${creditorId}`} download>Download</a>
readFile
返回一个 Buffer,它是原始字节。你将这些原始字节发送回客户端,客户端将其记录到控制台。你会看到body.text
,这是预期的。你需要使用fs.writeFile
或类似的方法将这些字节写入文件中。 - timothyclifford