将base64图片上传到Amazon S3 [英] Upload base64 image to amazon s3

查看:454
本文介绍了将base64图片上传到Amazon S3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试将图像上传到AWS S3时遇到一些问题.似乎可以正确上传文件,但是,每当我尝试下载或预览时,都无法打开它.当前,这是我正在使用的上传代码:

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.

推荐答案

这里的问题是您似乎正在上传图像的base64编码版本,而不是图像的原始字节.取$ image_base64并首先解码为原始字节 http://php.net/manual/zh/function.base64-decode.php .我敢肯定,如果您尝试在文本编辑器中打开这些图像",则会看到base64十六进制数据.

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.

这篇关于将base64图片上传到Amazon S3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆