3

リクエストでファイルのコンテンツをクライアントに送信しようとしていますが、Express が持っている唯一のドキュメントは、物理ファイルを必要とするダウンロード機能です。送信しようとしているファイルは S3 からのものなので、ファイル名とコンテンツしかありません。

ファイルのコンテンツとコンテンツ タイプおよびファイル名の適切なヘッダーを、ファイルのコンテンツと共に送信するにはどうすればよいですか?

例えば:

files.find({_id: id}, function(e, o) {
  client.getObject({Bucket: config.bucket, Key: o.key}, function(error, data) {
    res.send(data.Body);
  });
});
4

2 に答える 2

7

ファイルの種類は明らかにファイルによって異なります。これを見てください:

http://en.wikipedia.org/wiki/Internet_media_type

ファイルが正確に何であるかがわかっている場合は、これらのいずれかを応答に割り当てます (必須ではありません)。また、ファイルの長さを応答に追加する必要があります (可能な場合、つまりストリームでない場合)。添付ファイルとしてダウンロードできるようにする場合は、Content-Disposition ヘッダーを追加します。したがって、これを追加するだけで済みます。

var filename = "myfile.txt";
res.set({
    "Content-Disposition": 'attachment; filename="'+filename+'"',
    "Content-Type": "text/plain",
    "Content-Length": data.Body.length
});

注: Express 3.x を使用しています。

EDITContent-Length : 実際には、Express はコンテンツの長さをカウントするのに十分スマートなので、ヘッダーを追加する必要はありません。

于 2013-02-15T15:53:00.683 に答える
0

これは、ストリームを使用するのに最適な状況です。knoxライブラリを使用して物事を単純化します。Knoxは、ファイルをクライアントにパイプするために必要なヘッダーの設定を処理する必要があります

var inspect = require('eyespect').inspector();
var knox = require('knox');
var client = knox.createClient({
  key: 's3KeyHere'
  , secret: 's3SecretHere'
  , bucket: 's3BucketHer'
});
/**
 * @param {Stream} response is the response handler provided by Express
 **/
function downloadFile(request, response) {
  var filePath = 's3/file/path/here';
  client.getFile(filePath, function(err, s3Response) {
    s3Response.pipe(response);
    s3Response.on('error', function(err){
      inspect(err, 'error downloading file from s3');
    });

    s3Response.on('progress', function(data){
      inspect(data, 's3 download progress');
    });
    s3Response.on('end', function(){
      inspect(filePath, 'piped file to remote client successfully at s3 path');
    });
  });
}

npm install knox eyespect

于 2013-02-15T17:30:20.253 に答える