Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 464
yvan Coyaud Avatar asked Dec 18 '22 01:12

yvan Coyaud


1 Answers

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');
}
like image 55
yvan Coyaud Avatar answered Jan 02 '23 21:01

yvan Coyaud