1、准备工作
(1)开通阿里云OSS服务
(2)从阿里云OSS开发文档指引下载 OSS PHP SDK,放到项目 extend 目录下
2、修改配置文件
开通OSS服务后把相应的配置项填写即可(这里是ThinkPHP5
的config.php
)
'aliyun_oss' => [
'accessKeyId' => '',
'accessKeySecret' => '',
'endpoint' => '',
'bucket' => '',
'cdn' => ''
]
3、代码部分
use aliyun_oss\src\OSS\OssClient;
use aliyun_oss\src\OSS\Core\OssException;
public function uploadVideo()
{
//上传视频到阿里云OSS
$file = $_FILES['file'];
$name = $file['name'];
$format = strrchr($name, '.');
$fileName = uniqid() . $format;
//获取配置
$config = config('aliyun_oss');
$OssClient = new OssClient($config['accessKeyId'], $config['accessKeySecret'], $config['endpoint']);
$uploadToAliyunOss = $OssClient->uploadFile($config['bucket'], $fileName, $file['tmp_name']);
if ($uploadToAliyunOss) {
// 上传成功返回路径
return json(['videoUrl'=> $config['cdn'].strrchr($uploadToAliyunOss['info']['url'], '/')]);
} else {
// 上传失败,打印错误信息
halt($uploadToAliyunOss);
}
}