今天准备将文件直接通过PHP临时文件夹上传到S3存储桶中,
遇到一个问题, 就是上传临时文件, 用fopen之后的ContentType 就变成八进制资源类型了,
查找资料找到修改类型的配置,
'params' => [ 'ContentType' => $mime, ],
详细参考代码如下:
<?php namespace app\api\controller; use Aws\S3\S3Client; use Aws\Credentials\Credentials; use Aws\Exception\MultipartUploadException; use Aws\S3\MultipartUploader; use think\Controller; use think\Log; use think\Request; /** * thinkphp5 S3存储桶上传方法 * */ class Index extends Controller { public function index() { $this->S3FileUploadTemp( Request::instance()->file('file')->getPathname(), '123.jpg', Request::instance()->file('file')->getInfo('type') ); } /** * 加载s3客户端 * * @return S3Client */ public function AWS_S3Client(){ //证书 $credentials = new Credentials( 'AWSAccessKeyId', 'AWSSecretKey'); //s3客户端 return new S3Client([ 'version' => 'latest', //地区 亚太区域(新加坡) 'region' => '存储桶的地区',//自行配置 //加载证书 'credentials' => $credentials, //开启bug调试 //'debug' => true ]); } /** * AWS S3上传文件 * @param $file 上传文件 * @param string $filename S3中的文件名,用户自定义 * @param string $mime Content-Type * * * thinkphp5 中的用法 * * $this->S3FileUploadTemp( * Request::instance()->file('file')->getPathname(), * '123.jpg', * Request::instance()->file('file')->getInfo('type') * ); * * */ public function S3FileUploadTemp($file, $filename = '',$mime='') { // Create an S3Client $s3Client = $this->AWS_S3Client(); // 你的存储桶名称 $bucket = 'your-bucket'; // 待上传的文件路径或者对象资源 $source = $file; // $source = '/path/to/large/file.zip'; // $source = fopen($file, 'rb'); $uploader = new MultipartUploader($s3Client, $source, [ 'bucket' => $bucket, 'key' => $filename, 'ACL' => 'public-read', 'params' => [ 'ContentType' => $mime, ], ]); try { $result = $uploader->upload(); // 返回上传后的地址 $data = [ 'type' => '1', 'message' => urldecode($result['ObjectURL']) ]; } catch (MultipartUploadException $e) { Log::error($e->getMessage()); $data = [ 'type' => '0', 'message' => $e->getMessage() ]; } dump($data); // return $data; } }
参考博客地址
http://www.voidcn.com/article/p-mdtmcmev-bwa.html
https://www.cnblogs.com/guliang/p/14142982.html
获取安全凭证:
https://aws.amazon.com/blogs/security/wheres-my-secret-access-key/
https://console.aws.amazon.com/iam/home?#/security_credential
获取地区代码
https://docs.aws.amazon.com/general/latest/gr/rande.html