从nodejs中的服务器下载.zip文件 [英] download .zip file from server in nodejs

查看:5239
本文介绍了从nodejs中的服务器下载.zip文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用MEAN,其中我想允许用户从服务器下载zip文件。
所以我基本上要做以下事情:


  1. 从某些数据创建csv文件。

  2. 将该文件存储到某个目录中。

  3. 将这些文件压缩为zip。

  4. 当用户点击按钮时,


  5. 我已完成了1,2,3个完全,4个部分。在此我已经能够成功下载zip文件,但此文件是损坏的格式,我无法读取此文件。



    我的代码下载功能是这里:



    html:
    下载CSV报告



    角部分:

      $ 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 b $ b})。
    错误(function(data,status,headers,config){
    alertify.error(data);
    });
    };

    NodeJS:

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

    exports.downaloadAllCsv = function(req,res){

    var file ='我的zip文件的本地路径',
    filename = path.basename );

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

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

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


    解决方案

    我使用了一个名为express-zip的npm库这里: https://www.npmjs.com/package/express-zip



    使用Node 4.X和Express 4.X,我可以从浏览器下载zip文件。让它通过Angular工作是什么导致我自己的问题:
    客户端下载服务器生成的zip文件



    这里是我的服务器代码:



    具有express-zip的Node(4.X)代码:

      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设置Content-Type和content-disposition
    resp.zip(files,filename);
    },
    _errorCb)
    }
    });

    utils.getFileLocations(titles)一个promise其中文件是这样的数组:

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

    我的.zip文件没有损坏,可读。


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

    解决方案

    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.

    这篇关于从nodejs中的服务器下载.zip文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆