![](/img/trans.png)
[英]How to upload base64 encoded image to Amazon S3 without temporarily saving on file system with official PHP SDK?
[英]Upload base64 image to amazon s3
我在尝试将图像上传到AWS S3时遇到了一些问题。 它似乎正确上传文件,但每当我尝试下载或预览时,它都无法打开。 目前,这是我正在使用的上传代码:
<?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";
}
?>
因此,当我在上传图像文件后检查控制台时,它具有预期的大小,权限和标题,但正如我所说,每当我尝试打开文件时,它都会失败。
这可能是什么问题? 提前致谢。
这里的问题是你似乎正在上传图像的base64编码版本而不是图像的原始字节。 取$ image_base64并首先解码为原始字节http://php.net/manual/en/function.base64-decode.php 。 我相信如果你试图在文本编辑器中打开那些“图像”,你会看到base64十六进制数据。
您可以使用函数$ s3Client-> upload来“动态” 上传 ,如下例所示:
<?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');
我使用silex php 2.0和以下代码来源
$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']);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.