[英]File retrieval from AWS S3 to Node.js server, and then to React client
I have a need to retrieve individual files from Node.js with Express.js.我需要使用 Express.js 从 Node.js 检索单个文件。 For that, I have installed
aws-sdk
, as well as @aws-sdk/client-s3
.为此,我安装了
aws-sdk
以及@aws-sdk/client-s3
。 I am able to successfully fetch the file by using this simple endpoint:我可以使用这个简单的端点成功地获取文件:
const app = express(),
{ S3Client, GetObjectCommand } = require('@aws-sdk/client-s3'),
s3 = new S3Client({ region: process.env.AWS_REGION });
app.get('/file/:filePath', async (req,res) => {
const path_to_file = req.params.filePath;
try {
const data = await s3.send(new GetObjectCommand({ Bucket: process.env.AWS_BUCKET, Key: path_to_file }));
console.log("Success", data);
} catch (err) {
console.log("Error", err);
}
});
...but I have no idea how to return the data
correctly to the React.js frontend so that the file can be further downloaded. ...但我不知道如何将
data
正确返回到 React.js 前端,以便可以进一步下载文件。 I tried to look up the documentation, but it's looking too messy for me, and I can't even get what does the function return.我试图查找文档,但它看起来对我来说太乱了,我什至无法得到 function 返回的内容。
.toString()
method didn't help because it simply returns `"[object Object]" and nothing really else. .toString()
方法没有帮助,因为它只是返回 `"[object Object]" 而没有别的。
On React, I am using a library file-saver
, which works with blobs and provides them for download using a filename defined by user.在 React 上,我使用了一个库
file-saver
,它与 blob 一起使用,并使用用户定义的文件名提供它们以供下载。
Node v15.8.0, React v16.4.0, @aws-sdk/client-s3 v3.9.0, file-saver v2.0.5节点 v15.8.0、React v16.4.0、@aws-sdk/client-s3 v3.9.0、文件保护程序 v2.0.5
Thanks for your tips and advices.感谢您的提示和建议。 Any help is highly appreciated.
非常感谢任何帮助。
Generally data from S3 is returned as a buffer.通常来自 S3 的数据作为缓冲区返回。 The file contents are part of the
Body
param in the response.文件内容是响应中
Body
参数的一部分。 You might be doing toString
on the root object.您可能正在根 object 上执行
toString
。
You need to use .toString()
on the body param to make it a string.您需要在 body 参数上使用
.toString()
以使其成为字符串。
Here is some sample code that might work for use case这是一些可能适用于用例的示例代码
// Note: I am not using a different style of import
const AWS = require("aws-sdk")
const s3 = new AWS.S3()
const Bucket = "my-bucket"
async getObject(key){
const data = await s3.getObject({ Bucket, key}).promise()
if (data.Body) {return data.Body.toString("utf-8") } else { return undefined}
}
To return this in express
, you can add this to your route and pass the final data back once you have it.要在
express
中返回它,您可以将其添加到您的路线中,并在获得最终数据后将其传回。
res.end(data));
Consuming it in React should be the same as taking values from any other REST API.在 React 中使用它应该与从任何其他 REST API 获取值相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.