Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create and Send Zip file -NODE JS

I'm trying to create and then send zip file to client. I know how to create it but I've got a problem with send it to client. I tried many ways. I'm sending POST request from Client and as response I want to send a file. This is my server-site example code

var Zip = require('node-zip');
router.post('/generator', function(req, res, next) {
    var zip = new Zip;

    zip.file('hello.txt', 'Hello, World!');
    var options = {base64: false, compression:'DEFLATE'};
    fs.writeFile('test1.zip', zip.generate(options), 'binary', function (error) {
        console.log('wrote test1.zip', error);
    });
    res.setHeader('Content-disposition', 'attachment; filename=test1.zip');
    res.download('test1.zip');

}

}); I also tried something like this:

  res.setHeader('Content-disposition', 'attachment; filename=' + filename);
  res.setHeader('Content-type', mimetype);

  var filestream = fs.createReadStream(file);
  filestream.pipe(res);

I tried to use such libraries as:

  1. node-zip

  2. archiver

Can anyone explain me how to do that ?

like image 372
PtDf Avatar asked Oct 21 '15 13:10

PtDf


2 Answers

This module works fine too: https://www.npmjs.com/package/adm-zip

Example without creating temporary zip file in server:

var AdmZip = require('adm-zip');
router.get('/zipFilesAndSend', function(req, res) {
    var zip = new AdmZip();
    // add local file
    zip.addLocalFile("./uploads/29/0046.xml");
    // get everything as a buffer
    var zipFileContents = zip.toBuffer();
    const fileName = 'uploads.zip';
    const fileType = 'application/zip';
    res.writeHead(200, {
        'Content-Disposition': `attachment; filename="${fileName}"`,
        'Content-Type': fileType,
      })
    return res.end(zipFileContents);
});
like image 58
golimar Avatar answered Sep 19 '22 01:09

golimar


I haven't worked with node-zip or archiver before (I usually just use the built-in zlib module), but one thing I noticed right away is that you should place res.download inside the callback of writeFile. That way it will only send the file once it has been fully written to disk.

fs.writeFile('test1.zip', zip.generate(options), 'binary', function (error) {
    res.download('test1.zip');
});

I hope this solution works for you, if it doesn't feel free to comment.

Also, I think res.download sets the Content-disposition header for you, you don't need to set it manually. Not 100% sure on that one though.

like image 22
Wouter Avatar answered Sep 22 '22 01:09

Wouter