简体   繁体   中英

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.

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?

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM