2016-04-13 13 views
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); 

これは私にJSON形式としてnamebufferが含まれたテキストファイルresourceを返されました。

application/zipとしてcontentTypeを更新しても、テキスト形式で返されます。

このファイルを作成してフォルダに追加し、フォルダタイプをzipとして設定するにはどうすればよいですか?すべての

答えて

1

次のスニペットは、簡略化さを作成するためのadm-zipモジュールを使用することができ、公式ExpressのAPIから(http://expressjs.com/en/api.html

res.attachment([filename])を使用する必要があります私のために働くコードのバージョン。私はラッパーを取り除かなければならなかったので、理解しやすいので、バグが発生する可能性があります。

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

    }); 
関連する問題