accessKey = C('OBS_ACCESS_KEY'); $this->secretKey = C('OBS_SECRET_KEY'); $this->endpoint = C('OBS_ENDPOINT'); $this->domain = C('OBS_DOMAIN'); $this->bucket = C('OBS_BUCKET'); $this->client = new BaseObsClient([ 'key' => $this->accessKey, 'secret' => $this->secretKey, 'endpoint' => $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\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 delete($deleteFile) { $resp = $this->client->deleteObject([ 'Bucket' => $this->bucket, 'Key' => $deleteFile, ]); } public function getUrl($saveFileName) { return $this->domain . '/' . $saveFileName; } public function __destruct() { $this->client->close(); } }