//阿里云OSS配置'
alioss' =>[
'AccessKeyID'=> 'AccessKey ID',
'AccessKeySecret'=> 'Access Key Secret',
'EndPoint' => '外网访问地域节点',
'Bucket' => 'Bucket 名称',
'ossUrl' =>'https://www.baidu.com'
],
//在项目的根目录运行composer require aliyuncs/oss-sdk-php,或者在composer.json文件中添加如下依赖关系。
"require": {
"aliyuncs/oss-sdk-php": "~2.4"
}
//使用方法
<?php
namespace app\admin\controller;
use think\Controller;
use OSS\OssClient;
use OSS\Core\OssException;
use think\Db;
class Upload extends Controller
{
/**
* 调用阿里云OSS SDK
*/
public static function upload()
{
$file = request()->file('file');
try {
$KeyId = config('web.oss.KeyId');
$KeySecret = config('web.oss.KeySecret');
$EndPoint = config('web.oss.EndPoint');
$Bucket = config('web.oss.Bucket');
$ossUrl = config('web.oss.ossUrl');
//实例化
$ossClient = new OssClient($KeyId, $KeySecret, $EndPoint);
//获取文件类型
$ext = pathinfo($file->getInfo()['name'], PATHINFO_EXTENSION);
if(in_array($ext,['jpg','png','jpeg','gif'])){
$dirName = 'images';
}elseif (in_array($ext,['mp4','rmvb','avi','mkv'])){
$dirName = 'video';
}elseif(in_array($ext,['mp3','wma','m4a','acc'])){
$dirName = 'audio';
}else{
$dirName = 'file';
}
$fileName = str_replace('.'.$ext,'',$file->getInfo()['name']);
$filePath ='uploads/'.$dirName.'/'.sha1(date('YmdHis', time()) . uniqid()) . '.' . $ext;
//执行阿里云上传
$ossClient->uploadFile($Bucket, $filePath, $file->getInfo()['tmp_name']);
$url = $ossUrl.'/'.$filePath;
return ['code'=>201,'msg'=>'ok','url'=>$url];
} catch (OssException $e) {
return ['code'=>404,'msg'=>$e->getMessage()];
}
}
}