简体   繁体   中英

How to upload base64 encoded image to Amazon S3 without temporarily saving on file system with official PHP SDK?

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?

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.

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