使用createReadStream()传递到资源库时,在Node.js上的Express aws-sdk.s3.getObject()具有空缓冲区

时间:2018-07-26 16:11:34

标签: node.js express aws-sdk

有问题的代码,首先不尝试从响应中创建读取流:

app.get('/dashboard/downloadfile', requiresLogin, (req, res) => {
  const userid = req.user.id;
  const filename = req.query['file-name'];

  db.getFileKey([userid, filename], (keyres) => {
    const params = {
      Bucket: S3_BUCKET,
      Key: keyres.rows[0].filekey,
    };
    res.setHeader('Content-disposition', `attachment; filename=${ filename }`);
    res.setHeader('Content-type', 'text/plain');
    s3.getObject(params, (awserr, awsres) => {
      if(awserr) console.log(awserr);
      else console.log(awsres);
    });
  });
});

console.log(awsres);的结果

10:42:27 AM web.1 |  { AcceptRanges: 'bytes',
10:42:27 AM web.1 |    LastModified: 2018-07-23T23:27:29.000Z,
10:42:27 AM web.1 |    ContentLength: 2519,
10:42:27 AM web.1 |    ETag: '"5ebd5ec977c868605a6efe830df8ee0d"',
10:42:27 AM web.1 |    ContentType: 'text/plain',
10:42:27 AM web.1 |    Metadata: {},
10:42:27 AM web.1 |    Body: <Buffer 51 75 65 75 65 20 74 6f 56 69 73 69 74 0d 0a 53 65 74 20 76 69 73 69 74 65 64 0d 0a 0d 0a 0d 0a 66 69 6e 64 5f 6e 75 6d 5f 73 68 6f 72 74 65 73 74 5f ... > }

现在尝试从s3.getObject()响应创建读取流:

app.get('/dashboard/downloadfile', requiresLogin, (req, res) => {
  const userid = req.user.id;
  const filename = req.query['file-name'];

  db.getFileKey([userid, filename], (keyres) => {
    const params = {
      Bucket: S3_BUCKET,
      Key: keyres.rows[0].filekey,
    };
    res.setHeader('Content-disposition', `attachment; filename=${ filename }`);
    res.setHeader('Content-type', 'text/plain');
    s3.getObject(params, (awserr, awsres) => {
      if(awserr) console.log(awserr);
      else console.log(awsres);
    }).createReadStream().pipe(res);
  });
});

console.log(awsres);的结果

10:26:25 AM web.1 |  { AcceptRanges: 'bytes',
10:26:25 AM web.1 |    LastModified: 2018-07-23T23:27:29.000Z,
10:26:25 AM web.1 |    ContentLength: 2519,
10:26:25 AM web.1 |    ETag: '"5ebd5ec977c868605a6efe830df8ee0d"',
10:26:25 AM web.1 |    ContentType: 'text/plain',
10:26:25 AM web.1 |    Metadata: {},
10:26:25 AM web.1 |    Body: <Buffer > }

在这个问题中,我试图将文件通过管道传递给客户端,以尝试获取路由。我一生都想不通。

0 个答案:

没有答案