简体   繁体   中英

AWS S3 getObject to image

The 'getObject' request from the AWS S3 SDK returns a 'data.Body' such as 'Uint8Array (51213) [137, 80 ....'

How to transform this data to display it in an HTML tag

<img id='imgTest' .....


s3.getObject({
    Bucket: 'mybuket',
    Key: "test/myImage.png"
}, function (errtxt, data) {
    if (errtxt) {
        console.Log("lireImage", "ERR " + errtxt);
    } else {
        console.log('lecture OK')
        let imageTest =document.getElementById('imgTest')
        imageTest.src = ????

Thank you for your answers YC

I'm not looking for the URL of the image, because if I want to load this image from its URL, this image MUST BE declared 'public', otherwise there's a 403 (forbidden) error message.

That's why I'm loading the image with an 's3.getObject', with an 's3' declared and authenticated by my access keys. In this way, we can load an image declared private.

What I did not know how to do was convert the received data into an image.

In one of the links you gave me, I found the solution.

let imageTest =document.getElementById('imgTest')
s3.getObject({
    Bucket: 'myBucket',
    Key: "test/myimage.png"
}, function (errtxt, file) {
    if (errtxt) {
        console.Log("lireFic", "ERR " + errtxt);
    } else {
        console.log('lecture OK')
        imageTest.src = "data:image/png;base64," + encode(file.Body);
    }
});
function encode(data)
{
    var str = data.reduce(function(a,b){ return a+String.fromCharCode(b) },'');
    return btoa(str).replace(/.{76}(?=.)/g,'$&\n');
}

All you need to do is retrieve the url of the image you with to display.

See the following answers:

Amazon S3 Access image by url

display images fetched from s3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM