PHP-- AWS S3云存储上传多文件与上传单个文件
【摘要】
首先使用 composer在项目中下载aws:
composer require aws/aws-sdk-php
/* * AWS S3上传文件 * @param string $file 文件名称 * @re...
首先使用 composer在项目中下载aws:
composer require aws/aws-sdk-php
-
/*
-
* AWS S3上传文件
-
* @param string $file 文件名称
-
* @return array $path
-
*/
-
public function fileUpload($file){
-
//设置超时
-
set_time_limit(0);
-
//证书 AWS access KEY ID 和 AWS secret access KEY 替换成自己的
-
$credentials = new Aws\Credentials\Credentials('AWS access KEY ID ', 'AWS secret access KEY');
-
//s3客户端
-
$s3 = new Aws\S3\S3Client([
-
'version' => 'latest',
-
//地区 亚太区域(新加坡) AWS区域和终端节点: http://docs.amazonaws.cn/general/latest/gr/rande.html
-
'region' => 'ap-southeast-1',
-
//加载证书
-
'credentials' => $credentials,
-
//开启bug调试
-
//'debug' => true
-
]);
-
-
//存储桶 获取AWS存储桶的名称
-
$bucket = 'test';//'AWS存储桶名称';
-
//需要上传的文件
-
$source = ROOT_PATH.$file; //ROOT_PATH项目根目录,文件的本地路径例:D:/www/abc.jpg;
-
//多部件上传
-
$uploader = new Aws\S3\MultipartUploader($s3, $source, [
-
//存储桶
-
'bucket' => $bucket,
-
//上传后的新地址
-
'key' => $file,
-
//设置访问权限 公开,不然访问不了
-
'ACL' => 'public-read',
-
//分段上传
-
'before_initiate' => function (\Aws\Command $command) {
-
// $command is a CreateMultipartUpload operation
-
$command['CacheControl'] = 'max-age=3600';
-
},
-
'before_upload' => function (\Aws\Command $command) {
-
// $command is an UploadPart operation
-
$command['RequestPayer'] = 'requester';
-
},
-
'before_complete' => function (\Aws\Command $command) {
-
// $command is a CompleteMultipartUpload operation
-
$command['RequestPayer'] = 'requester';
-
},
-
]);
-
-
try {
-
$result = $uploader->upload();
-
//上传成功--返回上传后的地址
-
$data = [
-
'type' => '1',
-
'data' => urldecode($result['ObjectURL'])
-
];
-
} catch (Aws\Exception\MultipartUploadException $e) {
-
//上传失败--返回错误信息
-
$uploader = new Aws\S3\MultipartUploader($s3, $source, [
-
'state' => $e->getState(),
-
]);
-
$data = [
-
'type' => '0',
-
'data' => $e->getMessage();
-
];
-
}
-
return $data;
-
}
-
参考链接:https://blog.csdn.net/u011477914/article/details/88534191
官方操作文档:https://docs.aws.amazon.com/zh_cn/AmazonS3/latest/dev/mpuoverview.html
文章来源: blog.csdn.net,作者:lxw1844912514,版权归原作者所有,如需转载,请联系作者。
原文链接:blog.csdn.net/lxw1844912514/article/details/101274235
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)