* 加載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
]);
}
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];
}
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;
}?>