3

I am using MEAN, in which I want to allow user to download zip file from server. So basically I have to do following things:

  1. Create csv files from certain data.
  2. Store that file into some directory.
  3. Compress these file to zip.
  4. When a user clicks on the button, zipped file should be downloaded and readable.

I have achieved 1,2,3 completely, and 4 partially. In this I have been able to successfully download zip file, but this file is in corrupted format and I am not able to read this file.

My code for download functionality is here:

html: Download CSV Reports

angular part:

$scope.downloadFiles = function() {
    $http({
      method: 'GET',
      url: '/download/csv/files'
    }).
    success(function(data, status, headers, config) {
      var anchor = angular.element('<a/>');
      anchor.attr({
        href: 'data:attachment' + encodeURI(data),
        target: '_blank',
        download: 'filename.zip'
      })[0].click();
    }).
    error(function(data, status, headers, config) {
      alertify.error(data);
    });
  };

NodeJS:

    var path = require('path'),
        fs = require('fs');

    exports.downaloadAllCsv = function(req, res) {

    var file = 'local path to my zip file',
      filename = path.basename(file);

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

      res.setHeader('Content-type:',' application/zip');

      var filestream = fs.createReadStream(file);
      filestream.pipe(res);
     };
zulekha
  • 313
  • 9
  • 17

1 Answers1

0

I used an npm library called express-zip (found here: https://www.npmjs.com/package/express-zip)

Using Node 4.X and Express 4.X, I can download a zip file from my browser. Getting it to work through Angular is what lead me to my own question: Client download of a server generated zip file

Given all of that, here is my server code that worked:

Node (4.X) code with express-zip:

router.get('/bulkdownload',function(req,resp){
    var titles = req.query.titles || [];

    if ( titles.length > 0 ){
        utils.getFileLocations(titles).
        then(function(files){
            let filename = '/tmp/zipfile.zip';

            // .zip sets Content-Type and Content-disposition
            resp.zip(files,filename);
        },
        _errorCb)
    }
});

The utils.getFileLocations(titles) returns a promise where files is an array like this:

[{path: '/path/to/file/file.abc',name:'file.abc'},{...},{...},...]

My .zip file is not corrupted, and is readable.

Community
  • 1
  • 1
westandy
  • 1,360
  • 2
  • 16
  • 41