[英]Nodejs - how to upload file from req to aws s3
Working on web-app: React & Node.在 web 应用上工作:React 和 Node。
the client app sends file to the server, and the server should upload it to an S3 bucket
.客户端应用程序将文件发送到服务器,服务器应将其上传到S3 bucket
。
using import S3 from 'aws-sdk/clients/s3';
使用import S3 from 'aws-sdk/clients/s3';
i found the upload
function.我找到了upload
function。
The upload
function expect to get Buffer or Stream, and i don't know how to convert the file to buffer/stream. upload
function 期望获得 Buffer 或 Stream,我不知道如何将文件转换为缓冲区/流。
Code代码
app.get('/upload', (req, res) => {
const { file } = req;
s3.upload({ Bucket: 'MY_BUCKET', Key: 'MY_KEY', Body: streamifyFile(file)});
})
const streamifyFile = () => {
// how to implement
}
Solution:解决方案:
const uploadToS3 = async (req) => {
const {
file
} = req.body;
const { filename, createReadStream } = await file;
const pass = new stream.PassThrough();
const params = {
Bucket: process.env.S3_BUCKET,
Key: `${context.user.email}/${new Date().toISOString()}.${filename}`,
Body: pass,
};
const uploadPromise = s3.upload(params).promise();
const streamInput: Stream = createReadStream();
streamInput.pipe(pass);
const uploadData = await uploadPromise;
logger.info(
`Successfully upload - file: ${filename}, location: ${uploadData.Location}`,
);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.