[英]How to download a file .zip instead of a binary in JS?
I am trying to build a simple website with backend built with NodeJS + ExpressJS which allows users to download some ZIP files from the client.我正在尝试构建一个简单的网站,其后端使用 NodeJS + ExpressJS 构建,允许用户从客户端下载一些 ZIP 文件。
However when I tested the logic in Postman,the returned data was a string of symbols, indicating that it was a binary, not a.zip file.但是当我测试Postman中的逻辑时,返回的数据是一串符号,表明它是二进制文件,而不是.zip文件。
Here is the code snippet:这是代码片段:
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');
}
});
What do I have to do to make sure that the server gives me the.zip file instead of a binary?我该怎么做才能确保服务器给我.zip 文件而不是二进制文件?
It is because your file is not a zipped file, consider using ArchiverJs may solve your issue.这是因为您的文件不是压缩文件,考虑使用ArchiverJs可能会解决您的问题。
Code example:代码示例:
res.writeHead(200, { 'Content-Type': 'application/zip', 'Content-disposition': 'attachment; filename='+fileName }); let zip = Archiver('zip'); zip.pipe(res); zip.file(filePath, { name: fileName }).finalize();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.