如何将base64映像上传到s3存储桶。我正在使用CodeIgniter 3,图片将通过Rest API发布到服务器上
答案 0 :(得分:0)
This code works for me.Please check it
<?php
$image = $this->generateImage($_POST['foto']);
public function generateImage($img)
{
$folderPath = "uploads/";
$image_parts = explode(";base64,", $img);
$image_type_aux = explode("uploads/", $image_parts[0]);
$image_base64 = base64_decode($image_parts[1]);
$name = uniqid() . '.png';
$file = $folderPath . $name;
file_put_contents($file, $image_base64);
$this->saveImageAmazomS3($name);
}
function saveImageAmazomS3($image)
$filePath = base_url()."uploads/".$image;
require 'vendor/autoload.php';
$bucketName = 'YOUR_BUCKET_NAME';
$filePath = './YOUR_FILE_NAME.png';
$keyName = basename($filePath);
$IAM_KEY = 'YOUR_SECRET_ACCESS_KEY';
$IAM_SECRET = 'YOUR_SECRET_ACCESS_CODE';
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
// Set Amazon S3 Credentials
$s3 = S3Client::factory(
array(
'credentials' => array(
'key' => $IAM_KEY,
'secret' => $IAM_SECRET
),
'version' => 'latest',
'region' => 'us-east-2'
)
);
try {
if (!file_exists('/tmp/tmpfile')) {
mkdir('/tmp/tmpfile');
}
// Create temp file
$tempFilePath = '/tmp/tmpfile/' . basename($filePath);
$tempFile = fopen($tempFilePath, "w") or die("Error: Unable to open file.");
$fileContents = file_get_contents($filePath);
$tempFile = file_put_contents($tempFilePath, $fileContents);
// Put on S3
$s3->putObject(
array(
'Bucket'=>$bucketName,
'Key' => $keyName,
'SourceFile' => $tempFilePath,
'StorageClass' => 'REDUCED_REDUNDANCY'
)
);
} catch (S3Exception $e) {
echo $e->getMessage();
} catch (Exception $e) {
echo $e->getMessage();
}
}