javascript 通过NodeJs从浏览器上传图片到S3存储桶

ktca8awb  于 2023-06-20  发布在  Java
关注(0)|答案(3)|浏览(126)

我试图从浏览器上传图像到Amazon S3,下面的代码向Amazon S3发送了一些blob,我无法在浏览器中读取结果文件。它似乎不知道这是一个图像文件。
我从浏览器发送到NodeJS:

let myReader=new FileReader();
myReader.onloadend=(e)=>{ app.ws.send(myReader.result); }
myReader.readAsDataURL(e.target.files[0]);

在NodeJS中,我将其发送到S3:

const s3=new AWS.S3();
const params= { Bucket:<bucketName>, Key:fileName, Body:imgData, ACL:"public-read", ContentEncoding:'base64' };
s3.putObject(params, (err, data)=>{
    if (err) throw err; 
});
c2e8gylq

c2e8gylq1#

查看AWS S3指南,此文档包含将图像从浏览器上传到S3存储桶所需的逻辑
https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/s3-example-photo-album.html

gk7wooem

gk7wooem2#

原来你需要修改传入的base64图像数据,并显式设置ContentType:

const s3=new AWS.S3();
const type = imgData.split(';')[0].split('/')[1];
imgData= new Buffer.from(imgData.replace(/^data:image\/\w+;base64,/, ""), 'base64');
let params = { Bucket:<bucketName>, Key:fileName, Body:imgData, 
    ACL:"public-read", ContentType:"image."+type, ContentEncoding: 'base64' };

s3.upload(params, (err, data)=>{
    if (err) throw err;
    ... Do something ... 
    });
31moq8wy

31moq8wy3#

非常感谢你的分享,比尔。PutObjectCommand也有同样的问题。应用您的解决方案并工作!...

const client = new S3Client({});
const fileData = usr.fileData;
const fileName = usr.fileName;
const base64Buffer = new 
Buffer.from(fileData.replace(/^data:image\/\w+;base64,/, ""), 'base64');
const command = new PutObjectCommand({
    Bucket: 'test',
    Key: `avatar/${fileName}`,
    Body: base64Buffer,
    ContentType: 'image/png',
    ContentEncoding: 'base64',
    //ACL: 'public-read', // Set appropriate ACL based on your 
                                     requirements
});

try {
    const response = await client.send(command);
    console.log('Image uploaded successfully:');
} catch (err) {
    console.error('Error uploading image:', err);
    socket.emit('uploadError', { error: 'Failed to upload image' });
}

相关问题