我正在使用 AWS ec2 ubuntu 机器。我的代码在 cakephp 中。当我尝试将任何图像上传到 AWS S3 时,它会损坏。
虽然它在核心 php 代码中运行良好。
这是我的控制器代码
if ($this->User->saveAll($this->request->data)) {
// upload on s3
//create file name
// echo "<pre>"; print_r($_FILES); die;
$temp = explode(".", $_FILES["data"]["name"]["User"]['image']);
$newfilename = round(microtime(true)) . '.' . end($temp);
$filepath = $_FILES['data']['tmp_name']['User']['image'];
$id = $this->request->data['User']['id'];
try {
$result = $this->Amazon->S3->putObject(array(
'Signature' => 'v4',
'Bucket' => 'abc.sample',
'ACL' => 'authenticated-read',
'Key' => 'files/user/image/' . $id . "/" . $newfilename,
'ServerSideEncryption' => 'aws:kms',
'SourceFile' => $filepath,
'Body' => $filepath,
'ContentType' => $_FILES['data']['type']['User']['image'],
));
} catch (S3Exception $e) {
echo $e->getMessage() . "\n";
}
}
如果我不使用body
参数还有一件事,那么它会向我显示以下错误
您必须为 Body 或 SourceFile 参数指定一个非空值。
虽然以下代码适用于核心 php 中的测试
$filepath = "/var/www/html/for_testing_aws/assets/img/avtar.png";
try {
$result = $s3->putObject(array(
'Bucket' => $bucketName,
'ACL' => 'authenticated-read',
'Key' => "avtar-auth.png",
'ServerSideEncryption' => 'aws:kms',
'SourceFile' => $filepath,
'ContentType' => mime_content_type($filepath),
'debug' => [
'logfn' => function ($msg) {
echo $msg . "\n";
},
'stream_size' => 0,
'scrub_auth' => true,
'http' => true,
],
));
} catch (S3Exception $e) {
echo $e->getMessage() . "\n";
}
我创建了一个自定义组件来访问 SDK 的所有功能。参考https://github.com/Ali1/cakephp-amazon-aws-sdk。
检查这个
图像正确保存在我的 ec2 存储中。对于 ec2 服务器上的图像上传,我正在使用这个插件https://github.com/josegonzalez/cakephp-upload
我尝试putobject
使用简单的表单上传方法,这也适用于我这里是代码
require 'aws-autoloader.php';
$credentials = new Aws\Credentials\Credentials('key 1', 'key2');
$bucketName = "";
$s3 = new Aws\S3\S3Client([
// 'signature' => 'v4',
'version' => 'latest',
'region' => 'ap-southeast-1',
'credentials' => $credentials,
'http' => [
'verify' => '/home/ubuntu/cacert.pem'
],
'Statement' =>[
'Action '=> "*",
],
// 'debug' => [
// 'logfn' => function ($msg) {
// echo $msg . "\n";
// },
// 'stream_size' => 0,
// 'scrub_auth' => true,
// 'http' => true,
// ]
]);
$result = $s3->listBuckets();
foreach ($result['Buckets'] as $bucket) {
// Each Bucket value will contain a Name and CreationDate
$bucketName = $bucket['Name'];
}
<form name="uploadimage" id="uploadimage" method="post" action="saveimg.php" enctype="multipart/form-data">
<input type="file" name="file" value="file"/>
<input type="submit" name="submit" value="submit" />
</form>
和 saveimg.php 是
$filepath = $_FILES['file']['tmp_name'];
try {
$result = $s3->putObject(array(
'Bucket' => $bucketName,
'ACL' => 'authenticated-read',
'Key' => $_FILES['file']['name'],
'ServerSideEncryption' => 'aws:kms',
'SourceFile' => $filepath,
'ContentType' => mime_content_type($filepath),
'debug' => [
'logfn' => function ($msg) {
echo $msg . "\n";
},
'stream_size' => 0,
'scrub_auth' => true,
'http' => true,
],
));
} catch (S3Exception $e) {
echo $e->getMessage() . "\n";
}
当我尝试打开该文件时,显示了以下消息。