node.js
  • mongodb
  • 2016-04-13 41 views 1 likes 
    1

    我想以zip文件的形式下载数据库中的所有文件。动态创建多个文件nodejs

    如果我只想下载元素,我可以很容易地设置它的头和内容类型,然后可以发送它的缓冲区。

    db.collection("resource").find({}).toArray(function(err, result) { 
    res.setHeader('Content-disposition', 'attachment; filename=' + result[0].name); 
    res.contentType(result[0].mimetype); 
    res.send(result[0].data.buffer); 
    } 
    

    现在我想创建一个文件夹和每个result元素添加到该文件夹​​,然后将其发送。

    以下代码仅返回第一个文件。这是合理的,因为我立即发送缓冲区。

    for(var i=0; i < result.length; i++){ 
        res.setHeader('Content-disposition', 'attachment; filename=' + result[i].name); 
        res.send(result[i].data.buffer); 
    } 
    

    我想将它们添加到数组中。

    for(var i=0; i < result.length; i++){ 
        var obj = {name: result[i].name, buffer: result[i].data.buffer}; 
        files.push(obj); 
    } 
    
    
    res.setHeader('Content-disposition', 'attachment; filename=' + "resource"); 
    res.contentType('application/zip'); 
    res.send(files); 
    

    这回我一个文本文件resource其中包括namebuffer为JSON格式。

    即使我将contentType更新为application/zip,它将以文本格式返回。

    如何创建此文件,添加到文件夹并将文件夹类型设置为zip?

    回答

    0

    首先,你应该从官方快递API使用res.attachment([filename]),(http://expressjs.com/en/api.html

    你也可以使用adm-zip模块创建ZIP文件夹 (https://www.npmjs.com/package/adm-zip

    1

    下面的代码片断是一个简化一个适合我的代码版本。我不得不删除我的包装,以便更容易理解,所以这可能会导致一些错误。

    function bundleFilesToZip(fileUrls, next) { 
         // step 1) use node's fs library to copy the files u want 
         //   to massively download into a new folder 
    
    
         //@TODO: HERE create a directory 
         // out of your fileUrls array at location: folderUri 
    
         // step 2) use the tarfs npm module to create a zip file out of that folder 
    
         var zipUri = folderUri+'.zip'; 
         var stream = tarfs.pack(folderUri).pipe(fs.createWriteStream(zipUri)); 
         stream.on('finish', function() { 
         next(null, zipUri); 
         }); 
         stream.on('error', function (err) { 
         next(err); 
         }); 
        } 
    
        // step 3) call the function u created with the files u wish to be downloaded 
    
        bundleFilesToZip(['file/uri/1', 'file/uri/2'], function(err, zipUri) { 
        res.setHeader('Content-disposition', 'attachment; filename=moustokoulouro'); 
        // step 4) pipe a read stream from that zip to the response with 
        //   node's fs library 
        fs.createReadStream(zipUri).pipe(res); 
    
        }); 
    
    相关问题