【发布时间】:2022-01-16 14:37:48
【问题描述】:
我正在尝试构建一个简单的网站,其后端使用 NodeJS + ExpressJS 构建,允许用户从客户端下载一些 ZIP 文件。
但是我在Postman中测试逻辑时,返回的数据是一串符号,说明是二进制文件,不是.zip文件。
这里是sn-p的代码:
app.post('/', (req, res) => {
try {
const { specialID } = req.body;
if (!specialID) {
res.writeHead(400, { 'Content-Type': 'text/plain' });
return res.end('specialID needs to be specified');
}
const specialIDsMap = {
one: 1,
22: 2,
'33threee': 3,
};
const targetFile = specialIDsMap[specialID];
const filePath = `./zips/${targetFile}.zip`;
const fileName = 'test-file.zip';
fs.exists(filePath, (exists) => {
if (exists) {
res.writeHead(200, {
'Content-Type': 'application/octet-stream',
'Content-Disposition': 'attachment; filename=' + fileName,
});
fs.createReadStream(filePath).pipe(res);
} else {
res.writeHead(400, { 'Content-Type': 'text/plain' });
res.end('ERROR File does not exist');
}
});
我必须做些什么来确保服务器给我的是 .zip 文件而不是二进制文件?
【问题讨论】:
标签: node.js express fs content-type content-disposition