Nodejs Express发送文件

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

如果您将文件存储在本地,可以使用 res.download(http://expressjs.com/api.html#res.download)函数。 - Connor Leech
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。

编辑:实际上,Express足够智能,可以为您计算内容长度,因此您不必添加Content-Length头。


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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接