Ter*_*ker 12 javascript amazon-s3 amazon-web-services node.js
我正在尝试使用 NodeJS 应用程序将文件从 s3 存储桶发送到客户端。这是我到目前为止所拥有的:
import { S3 } from '@aws-sdk/client-s3';
const BUCKET_NAME = process.env.S3_BUCKET_NAME;
const s3 = new S3({
region: 'ap-southeast-2',
httpOptions: {
connectTimeout: 2 * 1000,
timeout: 60 * 1000,
},
});
router.get('/download/:id', async (req, res) => {
console.log('api: GET /download/:id');
console.log('req.params.id: ', req.params.id);
const result = await getRequiredInfo(req.params.id);
if (typeof result !== 'number') {
res.attachment(result.filename);
await s3
.getObject({
Bucket: BUCKET_NAME,
Key: result.location,
})
.createReadStream()
.pipe(res);
} else {
res.sendStatus(result);
}
});
Run Code Online (Sandbox Code Playgroud)
当我运行这段代码时,我收到以下信息:
(node:11224) UnhandledPromiseRejectionWarning: TypeError: s3.getObject(...).createReadStream is not a function
Run Code Online (Sandbox Code Playgroud)
我对 SO 感到好奇,看起来其他人在使用 getObject 和 createReadStream 的组合方面工作得很好。我现在缺少什么吗?我应该如何在响应中以流形式发送文件?
小智 17
.createReadStream()
是 aws-sdk v2 中的一个方法。@aws-sdk/client-s3
是 aws-sdk v3 的一部分。
要从 v3 获取流,您需要执行以下操作:
const response = await s3.getObject({
Bucket: BUCKET_NAME,
Key: key,
});
response.Body.pipe(res);
Run Code Online (Sandbox Code Playgroud)
有关 aws-sdk v3 的更多信息:https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-s3/
归档时间: |
|
查看次数: |
19707 次 |
最近记录: |