0

I have a "screenshot" of a div using a javascript library named html2canvas. It returns the "screenshot" as base 64 encoded image which I then pass to my PHP server using AJAX. The server will then temporarily save the image at the file system, upload the image to Amazon S3 and then immediately delete the file. It works, but I would like to see if it is possible to upload the image directly without saving to file system.

I know that there is a way to directly upload image through client side javascript, but I don't want to enable CORS. Also, I have found a solution for Node.js, so I guess there got to be a way to do it in PHP as well.

I noticed that there are somebody asking similar question, but there are no answer to that question, and the situation is a bit different, as I am using the official PHP SDK with the official service provider for laravel

So, is there a way I can directly upload a base64 encoded image to Amazon S3 without temporarily saving on file system?

Community
  • 1
  • 1
cytsunny
  • 4,838
  • 15
  • 62
  • 129
  • put_object need a file handler. So you need to check php code for ways to throw in file-like I/O object, perhaps you should look into the serialize library. – mootmoot Dec 20 '16 at 13:05

1 Answers1

0

Skip this step if your string is the correct output, but if you need to "save" from a GD image, then you can save the image to string using ob controls:

ob_start();
imagepng($image);
$pngData = ob_get_clean();
ob_end_clean();

Then you can simply specify Body to upload a string directly, and not a file.

$aParams = [
    'Bucket'     => $bucketName,
    'Key'        => $destName,
    'Body'       => $string,
    'ACL'        => 'public-read'
]);
$result = $s3Client->putObject($aParams);

You can also optionally add image headers etc as you would for uploading the file.

Robbie
  • 17,605
  • 4
  • 35
  • 72
  • Should that be 'Body' => $pngData instead? Also, for base64 encoded data, the string of image can be got by simply base64_decode? – cytsunny Dec 21 '16 at 02:19
  • Just try it - you're not going to break anything :) But yes, yes and yes (you have it all). Why different variable:- the snippets I grabbed are from different functions/classes (i.e. I have an `AmazonS3Handler::uploadString($string)` method, which is why it's $string, and the other snipeet was to differentiate from $jpgData which I use in another function. And yes, `base64_decode()`. – Robbie Dec 21 '16 at 03:01