user2202098 user2202098 - 1 month ago 9
jQuery Question

Post request for S3 image file

I have a php script to pull an image file from amazon S3 called

test.php

if I write the html like this
<img src="test.php">
The image appears fine.

However when I try to use a get request and set the SRC of the image it doesnt appear correctly. I eventually want to pass params in using post once this works. On inspecting the
src
its filled with meta data as if header("Content-type: image") hasnt been set.

$.get( "test.php",function( data ) {
$('#image1').attr('src', data);

});


My test.php script:

require '../vendor/autoload.php';
use Aws\S3\S3Client;

$region = 'us-west-2';
$bucket = 'mybucket';
$key = 'mykey';
$secret = 'mysecret';


$s3Client = new S3Client([
'version' => 'latest',
'region' => $region,
'credentials' => [
'key' => $key,
'secret' => $secret,
],
]);

$result = $s3Client->getObject(array(
'Bucket' => $bucket,
'Key' => 'monkey1.jpg'

));
header("Content-type: image");
// Print the body of the result by indexing into the result object.
echo $result['Body'];
//echo '<img src="'.$result['Body'].'">'

Answer

This worked for me.

PHP script

$s3Client = new S3Client([
    'version'     => 'latest',
    'region'      => $region,
    'credentials' => [
        'key'    => $key,
        'secret' => $secret,
    ],
]);

$s3Client->registerStreamWrapper();
if (file_exists('s3://'.$bucket.'/'.$id.'/'.$filepath)) {
    //echo 'It exists!';
    $result = $s3Client->getObject(array(
    'Bucket' => $bucket,
    //'Key'    => 'monkey1.jpg'
    'Key'    => $id.'/'.$filepath
    ));
    header("Content-type: image/*");
    // Print the body of the result by indexing into the result object.
    echo base64_encode($result['Body']);
}

JS

$('#image').attr('src', 'data:image/*;base64,'+data);