【问题标题】:Files downloaded from Amazon S3 using Knox and Node.js are corrupt使用 Knox 和 Node.js 从 Amazon S3 下载的文件已损坏
【发布时间】:2015-11-04 08:52:26
【问题描述】:

我正在使用 knox 访问我的 Amazon S3 存储桶以进行文件存储。我正在存储各种文件——主要是 MS Office 和 pdf,但可能是二进制文件或任何其他类型的文件。我还使用express 4.13.3 和busboyconnect-busboy 来支持流式传输;上传文件时,我使用 busboy 处理,然后通过 knox 直接到 S3,因此不必先将它们写入本地磁盘。

文件上传正常(我可以使用Transmit 手动浏览和下载它们)但我在下载时遇到问题。

为了清楚起见,我不想将文件写入本地磁盘,而是将其保存在内存缓冲区中。这是我用来处理 GET 请求的代码:

// instantiate a knox object
var s3client = knox.createClient({
  key: config.AWS.knox.key,
  secret: config.AWS.knox.secret,
  bucket: config.AWS.knox.bucket,
  region: config.AWS.region
});

var buffer = undefined;

s3client.get(path+'/'+fileName)
.on('response', function(s3res){

  s3res.setEncoding('binary');

  s3res.on('data', function(chunk){
    buffer += chunk;
  });

  s3res.on('end', function() {
    buffer = new Buffer(buffer, 'binary');
    var fileLength = buffer.length;
    res.attachment(fileName);
    res.append('Set-Cookie', 'fileDownload=true; path=/');
    res.append('Content-Length', fileLength);
    res.status(s3res.statusCode).send(buffer);
  });

}).end();

文件下载到浏览器 - 我使用的是 John Culviner 的 jquery.fileDownload.js - 但下载的文件已损坏且无法打开。如您所见,我使用 express'.attachment 设置 mime 类型的标头,使用 .append 设置附加标头(使用 .set 没有区别)。

当文件在 Chrome 中下载时,我看到消息“Resource interpreted as Document but transferred with MIME type application/vnd.openxmlformats-officedocument.spreadsheetml.sheet:”(对于 Excel 文件),因此 express 正确设置了标题,并且下载的文件大小与我在检查存储桶时看到的匹配。

有什么想法吗?

【问题讨论】:

    标签: amazon-s3 knox-amazon-s3-client busboy


    【解决方案1】:

    看起来内容可能不会以二进制形式发送到浏览器。尝试以下方法:

    if (s3Res.headers['content-type']) {
      res.type( s3Res.headers['content-type'] );
    }
    res.attachment(fileName);
    
    s3Res.setEncoding('binary');
    s3Res.on('data', function(data){
      res.write(data, 'binary');
    });
    
    s3Res.on('end', function() {
      res.send();
    });
    

    它还会在数据进入时一次发送一个数据块,因此它应该更节省内存。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-05
      • 2014-04-01
      • 1970-01-01
      • 2016-09-22
      • 1970-01-01
      • 2014-10-05
      • 1970-01-01
      相关资源
      最近更新 更多