Reputation: 37
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.
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.
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?
Upvotes: 0
Views: 1033
Reputation: 685
It is because your file is not a zipped file, consider using ArchiverJs may solve your issue.
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();
Upvotes: 1