From 5aab375f7cd4f173f54f7435a91309ca26f0d25e Mon Sep 17 00:00:00 2001 From: elf <360197197@qq.com> Date: Thu, 2 Feb 2023 23:40:14 +0800 Subject: [PATCH] =?UTF-8?q?=E5=90=B8=E6=80=AA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Application/Base/Service/ObsService.class.php | 109 ++++++++++++++++++ 1 file changed, 109 insertions(+) create mode 100644 Application/Base/Service/ObsService.class.php diff --git a/Application/Base/Service/ObsService.class.php b/Application/Base/Service/ObsService.class.php new file mode 100644 index 000000000..a570f5a29 --- /dev/null +++ b/Application/Base/Service/ObsService.class.php @@ -0,0 +1,109 @@ +accessKey = C('OBS_ACCESS_KEY'); + $this->secretKey = C('OBS_SECRET_KEY'); + $this->endpoint = C('OBS_ENDPOINT'); + $this->domain = C('OBS_DOMAIN'); + $this->isCName = C('OBS_IS_CNAME'); + $this->bucket = C('OBS_BUCKET'); + $this->client = new ObsClient($this->accessKey, $this->secretKey, $this->endpoint); + } + + public function upload($localFilePath, $saveFileName) + { + /* $resp = $this->client->putObject([ + 'Bucket' => $this->bucket, + 'Key' => $saveFileName, + 'SourceFile' => $localFilePath, + ]); */ + try { + $this->multiuploadFile($localFilePath, $saveFileName); + return [ + 'status' => true, + 'message' => '上传OSS成功', + 'data' => [ + 'url' => $this->getUrl($saveFileName) + ] + ]; + } catch (Obs\Common\ObsException $e) { + return [ + 'status' => false, + 'message' => $e->getExceptionMessage() + ]; + } + } + + private function multiuploadFile($file, $saveFileName) + { + $resp = $this->client->initiateMultipartUpload([ + 'Bucket' => $this->bucket, + 'Key' => $saveFileName, + 'ContentType' => 'text/plain' + ]); + $uploadId = $resp['UploadId']; + + $packetSize = 1048576; + $byteTotal = filesize($file); + $packetTotal = ceil($byteTotal / $packetSize); + $fileContent = fopen($file, 'r'); + $parts = []; + for ($i=0; $i<$packetTotal; $i++) { + $packetFileContent = fread($fileContent, $packetSize); + $resp = $this->client->uploadPart([ + 'Bucket' => $this->bucket, + 'Key' => $saveFileName, + 'UploadId' => $uploadId, + 'PartNumber' => $i+1, + 'Body' => $packetFileContent + ]); + $parts[] = ['PartNumber' => $i+1, 'ETag' => $resp['ETag']]; + } + fclose($fileContent); + + $resp = $this->client->completeMultipartUpload([ + 'Bucket' => $this->bucket, + 'Key' => $saveFileName, + 'UploadId' => $uploadId, + 'Parts' => $parts + ]); + } + + public function deleteObject($deleteFile) + { + $resp = $this->client->deleteObject([ + 'Bucket' => $this->bucket, + 'Key' => $deleteFile, + ]); + } + + public function getUrl($saveFileName) + { + return $this->domain . '/' . $saveFileName; + } + + public function __destruct() + { + $this->client->close(); + } +} \ No newline at end of file