node.js
  • mongodb
  • 2016-04-13 42 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); 
    
        }); 
    
    相關問題