You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

113 lines
3.1 KiB
PHP

<?php
namespace Base\Tool;
use Base\Tool\StorageClient;
use Obs\ObsClient as BaseObsClient;
/**
* 华为云OBS
*/
class ObsClient implements StorageClient
{
const MAX_PART_SIZE = 5368709120;
const MID_PART_SIZE = 10485760;
const MIN_PART_SIZE = 102400;
private $accessKey;
private $secretKey;
private $endpoint;
private $bucket;
private $domain;
private $client;
public function __construct()
{
$this->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();
}
}