当前位置: 首页 > 工具软件 > S3Uploader > 使用案例 >

php上传照片到s3云服务器,PHP上传文件到AWS S3&生成下载文件URL

俞俊逸
2023-12-01

* 加载s3客户端

* @return string*/

functionAWS_S3Client(){$ACCESS_KEY_ID = ‘你的s3 ID‘;$SECRET_ACCESS_KEY = ‘你的s3 秘钥‘;$credentials = new Aws\Credentials\Credentials($ACCESS_KEY_ID, $SECRET_ACCESS_KEY);return newAws\S3\S3Client([‘version‘ => ‘latest‘,

‘region‘ => ‘eu-central-1‘,//节点

‘credentials‘ => $credentials,

//‘debug‘ => true

]);

}/**

* AWS S3上传文件

* @param string $file 文件相对路径

* @param string $fileName 上传后的文件名称

* @param int $type 1使用断点续传,0不使用

* @param bool $publicRead 是否开放访问

* @return array $path*/

function S3FileUpload($file = ‘‘, $fileName = ‘‘, $type = 0, $publicRead = false)

{$s3Client =AWS_S3Client();$bucket = ‘yourBucketName‘;//你的存储桶名称

$source = FILE_UPLOAD . $file;//$source 需要绝对路径 注意更换成自己的目录配置

$fileName = $fileName ? $fileName : $file;$config =[‘bucket‘ => $bucket, ‘key‘ => $fileName,//这里如果是相对路径 如 test/img/1.png 会自动创建目录 如果是绝对路径则直接上传到指定的存储桶中

];//是否开放访问

if ($publicRead) {$config[‘ACL‘] = ‘public-read‘;

}$uploader = new Aws\S3\MultipartUploader($s3Client, $source, $config);$code = 0;$message = ‘‘;if ($type == 1) {//在分段上传过程中发生错误,重新开始未完成的上传。

do{try{$result = $uploader->upload();

}catch (Aws\Exception\MultipartUploadException $e) {$uploader = new Aws\S3\MultipartUploader($s3Client, $source,[‘state‘ => $e->getState(),]);

}

}while (!isset($result));$code = 1;$message = urldecode($result[‘ObjectURL‘]);

}else{try{$result = $uploader->upload();$code = 1;$message = urldecode($result[‘ObjectURL‘]);

}catch (Aws\Exception\MultipartUploadException $e) {$message = $e->getMessage();

}

}return [‘code‘ => $code, ‘message‘ => $message];

}/**

* 生成AWS S3下载文件url地址

* @param string $file 文件相对地址 如:test/img/1.png

* @param string $expires 授权时间

* @return string*/

function S3FileDownload($file, $expires = ‘+10 minutes‘)

{$s3Client =AWS_S3Client();$cmd = $s3Client->getCommand(‘GetObject‘,[‘Bucket‘ => ‘你的存储桶名称‘, ‘Key‘ => $file //相对地址

]);$request = $s3Client->createPresignedRequest($cmd, $expires);//创建预签名 URL

$presignedUrl = (string)$request->getUri();return $presignedUrl;

}?>

 类似资料: