cxgj/components/Oss.php
2024-01-19 14:25:27 +08:00

67 lines
1.7 KiB
PHP

<?php
namespace app\components;
use OSS\Core\OssException;
use OSS\OssClient;
class Oss
{
private $accessKeyId, $accessKeySecret, $bucket, $endpoint;
/**
* Oss constructor.
* @param $accessKeyId
* @param $accessKeySecret
* @throws \Exception
*/
public function __construct()
{
$this->accessKeyId = 'LTAI5tMaDbEbWyQWpwmxp24y';
$this->accessKeySecret = '3bjqbBFC08YIub3c8ry9Elz05UF1J7';
$this->bucket = 'cxgjsz1';
$this->endpoint = 'https://oss-cn-shenzhen.aliyuncs.com';
try {
if (!isset($this->client)) {
$this->client = $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint, false);
}
} catch (OssException $e) {
return $e->getMessage();
}
}
/**
* 上传文件到oss并删除本地文件
* @param $file
* @return bool|string
*/
public function upload($file)
{
$ext = explode('.', $file);
$ext = end($ext);
$date = date('Ymd');
$file_name = md5(time() . uniqid());
$oss_path = "upload/{$date}/{$file_name}.{$ext}";
// $file = \Yii::$app->basePath . '/web' . $file;
if (file_exists($file)) {
try {
$oss_client = $this->client->uploadFile($this->bucket, $oss_path, $file);
} catch (OssException $e) {
return $e->getMessage();
}
if (isset($oss_client['info']['url'])) {
// 自动删除本地的文件
unlink($file);
return $oss_client['info']['url'];
} else {
return $oss_client;
}
}
return false;
}
}