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