composer require aliyuncs/oss-sdk-php
use OSS\OssClient;
protected $config;
public function _initialize()
{
parent::_initialize();
$this->config = [
'KeyId' => config('alioss.KeyId'),
'KeySecret' => config('alioss.KeySecret'),
'Endpoint' => config('alioss.Endpoint'),
'Bucket' =>config('alioss.Bucket'),
];
}
public function saveImg()
{
$file = request()->file('imgFile');
$ioss = $this->ossUploadFile($file);
return $this->jsonSuccess('上传成功', ['src'=>$ioss]);
}
public function ossUploadFile($file)
{
if (empty($file)){
return $this->jsonError('上传失败');
}
$name = $file->getInfo()['name'];
$ext = explode('.', $name)[1];
$resResult = sha1(date('YmdHis', time()) . uniqid()) . '.' . $ext;
try {
$ossClient = new OssClient($this->config['KeyId'], $this->config['KeySecret'], $this->config['Endpoint']);
$fileName = 'img/' . sha1(date('YmdHis', time()) . uniqid()) . '.' . $resResult;
$result = $ossClient->uploadFile($this->config['Bucket'], $fileName, $file->getInfo()['tmp_name']);
$arr = [
'imgurl' => $result['info']['url'],
'dbimgName' => $fileName
];
$result = $result['info']['url'];
return $result;
} catch (OssException $e) {
echo returnData(-1,$e->getMessage());
}
}
|