我正在尝试在 NodeJS/Express 中创建一个端点,用于从我的 AWS S3 存储桶下载内容。
它运行良好,我可以在客户端下载文件,但我也可以在“网络”选项卡中看到流预览,这很烦人......
QUESTION
我想知道我所做的是否正确并且是一个好的做法。
还想知道在“网络”选项卡中看到输出流是否正常。
我应该如何使用 NodeJS/Express 将文件从 S3 正确发送到我的客户端应用程序?
我很确定其他网站请求不允许您预览内容:“无法加载响应数据".
这是我在 NodeJS 应用程序中从 AWS S3 获取流文件的操作:
download(fileId) {
const fileObjectStream = app.s3
.getObject({
Key: fileId
})
.createReadStream();
this.res.set("Content-Type", "application/octet-stream");
this.res.set(
"Content-Disposition",
'attachment; filename="' + fileId + '"'
);
fileObjectStream.pipe(this.res);
}
在客户端我可以看到:
我认为问题出在标题上:
//this line will set proper header for file and make it downloadable in client's browser
res.attachment(key);
// this will execute download
s3.getObject(bucketParams)
.createReadStream()
.pipe(res);
所以代码应该是这样的(这就是我在项目处理文件中作为 res.attachment 或 res.json 所做的,以防出现错误,以便客户端可以向最终用户显示错误):
router.route("/downloadFile").get((req, res) => {
const query = req.query; //param from client
const key = query.key;//param from client
const bucketName = query.bucket//param from client
var bucketParams = {
Bucket: bucketName,
Key: key
};
//I assume you are using AWS SDK
s3 = new AWS.S3({ apiVersion: "2006-03-01" });
s3.getObject(bucketParams, function(err, data) {
if (err) {
// cannot get file, err = AWS error response,
// return json to client
return res.json({
success: false,
error: err
});
} else {
res.attachment(key); //sets correct header (fixes your issue )
//if all is fine, bucket and file exist, it will return file to client
s3.getObject(bucketParams)
.createReadStream()
.pipe(res);
}
});
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)