I'm having some issues when trying to upload an image to AWS S3. It seems to upload the file correctly but, whenever I try to download or preview, it can't be opened. Currently, this is the upload code I'm using:
<?php
require_once 'classes/amazon.php';
require_once 'includes/aws/aws-autoloader.php';
use Aws\S3\S3Client;
$putdata = file_get_contents("php://input");
$request = json_decode($putdata);
$image_parts = explode(";base64,", $request->image);
$image_type_aux = explode("image/", $image_parts[0]);
$image_type = $image_type_aux[1];
$image_base64 = $image_parts[1];
$dateTime = new DateTime();
$fileName = $dateTime->getTimestamp() . "." . $image_type;
$s3Client = S3Client::factory(array(
'region' => 'eu-west-1',
'version' => '2006-03-01',
'credentials' => array(
'key' => Amazon::getAccessKey(),
'secret' => Amazon::getSecretKey(),
)
));
try {
$result = $s3Client->putObject(array(
'Bucket' => Amazon::getBucket(),
'Key' => 'banners/' . $fileName,
'Body' => $image_base64,
'ContentType' => 'image/' . $image_type,
'ACL' => 'public-read'
));
echo $result['ObjectURL'] . "\n";
} catch(S3Exception $e) {
echo $e->getMessage() . "\n";
}
?>
So, when I check the console after uploading the image file, it has the expected size, permissions and headers but, as I said, whenever I try to open the file, it fails.
What could be the problem here? Thanks in advance.
The issue here is you appear to be uploading the base64 encoded version of the image and not the raw bytes of the image. Take $image_base64 and decode into raw bytes first http://php.net/manual/en/function.base64-decode.php . I am sure if you tried to open those "images" in a text editor you would see base64 hex data.
you can upload "on the fly" by using the function $s3Client->upload like the following example:
<?php
$bucket = 'bucket-name';
$filename = 'image-path.extension';
$imageData = base64_decode(end(explode(",", $base64)));
$upload = $s3Client->upload($bucket, $filename, $imageData, 'public-read');
$upload->get('ObjectURL');
I use silex php 2.0 and the following code fount
$s3 = $app['aws']->createS3();
$putdata = file_get_contents("php://input");
$data = json_decode($request->getContent(), true);
$data = (object) $data;
$image_parts = explode(";base64,", $data->image);
$image_type_aux = explode("image/", $image_parts[0]);
$image_type = $image_type_aux[1];
$image_base64 = base64_decode($image_parts[1]);
$result = $s3->putObject([
'ACL' => 'public-read',
'Body' => $image_base64,
'Bucket' => 'name-bucket',
'Key' => 'test_img.jpeg',
'ContentType' => 'image/' . $image_type,
]);
var_dump($result['ObjectURL']);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With