对接-阿里云oss对象存储使用记录
说明
需要把部分资源放到阿里云OSS上,只做了简单的上传和下载的示例, 然后把调研及开发过程记录一下
相关文档
<h5>oss介绍</h5>
oss介绍: https://help.aliyun.com/document_detail/31817.html?spm=5176.11065259.1996646101.searchclickresult.538b84eahtDYEv
PHP_SDK手册:https://help.aliyun.com/document_detail/32099.html?spm=a2c4g.11186623.6.1052.675d65d3DqogAp
PHP SDK下载:https://github.com/aliyun/aliyun-oss-php-sdk?spm=a2c4g.11186623.2.9.29172215PQ1G40
<h5>技术文</h5>
https://www.cnblogs.com/zx-admin/p/7132952.html
https://blog.csdn.net/wen_3370/article/details/86583949
https://baijunyao.com/article/68
开发记录
<h5>步骤</h5>
1.登录自己的阿里云开通oss对象存储服务
2.创建RAM 测试用户,拿到 AccessKey ID和AccessKeySecret
3.创建Bucket 区域,获取到Bucket和Endpoint,创建Bucket时,权限要设置成公共读
<h5>部分截图</h5>



代码示例
<h5>安装</h5>
PHP SDK下载:https://github.com/aliyun/aliyun-oss-php-sdk?spm=a2c4g.11186623.2.9.29172215PQ1G40
composer安装:composer require aliyuncs/oss-sdk-php
<h5>配置alioss.conf</h5>
return [
//根据存储类型配置存储信息
'video'=>[
/*
|--------------------------------------------------------------------------
| 基础配置
|--------------------------------------------------------------------------
|
| 阿里云对象存储最基础配置项,相关数据请至阿里云对象存储控制台获取。
|
*/
'oss_key' => 'LTAI**************jhihU1',
'oss_secret' => 'o5NC7n7*********uylJ8XfN',
/*
|--------------------------------------------------------------------------
| 对象存储域配置
|--------------------------------------------------------------------------
|
| 对象上传至阿里云,指定存放域。
|
*/
'oss_endpoint' => 'oss-cn-beijing.aliyuncs.com',
'oss_bucket' => 'aicl*****',
'oss_bucket_host' => 'aic*****oss-cn-beijing.aliyuncs.com',
],
];
<h5>uploadController</h5>
上传对外接口放在controller
public function uploadFile1() //视频上传
{
if(!isset($_FILES['file'])){
$this->msg = new Msg(1,'视频上传参数{file}传递有误,请检查。');die;
}
$beid = $this->beid ? $this->beid : Request::get('beid');
$video = UploadService::videoUploadOss1('file',Constant::video,$beid);
if($video){
$this->msg = new Msg(0,'视频上传成功',$video);die;
}else{
$this->msg = new Msg(1,'视频上传失败,请选择正确的文件格式!');die;
}
}
<h5>uploadService</h5>
所用框架用了service模式,所有逻辑处理放在了service下
public static function videoUploadOss1($fileKey,$type,$beid){
//防止上传视频超时
set_time_limit(0);
self::init($type);
//限制上传大小
if($_FILES[$fileKey]["size"] > 1024*1024*50){
throw new APIException('视频大小不能超过50M',-13);
}
//限制上传文件是否有误
if($_FILES[$fileKey]["error"] > 0){
throw new APIException('文件上传失败,错误码为:'.$_FILES["file"]["error"], -13);
}
//验证上传格式
$arr = ['mp4'];//视频格式限制,只上传MP4
$ext = pathinfo($_FILES[$fileKey]['name'], PATHINFO_EXTENSION);//获取的后缀
if(!in_array($ext,$arr)){
throw new APIException('视频类型不正确,只支持 mp4| 1种格式',-11);
}
// 验证是否重复上传 | 根据场景设置
$tmpFile = $_FILES[$fileKey]["tmp_name"];
$md5 = md5(file_get_contents($tmpFile));
$existImage = self::getFileByMd5($md5);
if(!empty($existImage)){
if($md5 == $existImage['md5']){
return $existImage;
}
}
//拼接存储路径及绝对路径
$filename = self::newFileName();
$dst = self::getLocalFilePath($type);
$fileDst = $dst['fileDst'].'/'.$filename.'.'.$ext;
$relativeDst = $dst['resDst'].'/'.$filename.'.'.$ext;
//上传移动到真实路径
move_uploaded_file($tmpFile,$fileDst);
//删除本地文件
//unlink($fileDst);
//上传到阿里云 Oss
$ret = OssService::writeStream($relativeDst,$fileDst,'video');
$videoModel = new Video();
$addInfo=[
'name' => $_FILES[$fileKey]['name'],
'url' => $relativeDst,
'cover' => $ret,
'md5' => $md5,
'type' => $type,
'beid' => $beid,
'upload_time' => time(),
];
if($videoModel->insert($addInfo)){
return [
'localArr'=>Config::get('app')['cosVideoHost'].$relativeDst,
'ossArr'=>$ret,
];
}else{
unlink($relativeDst);
OssService::deleteStream($relativeDst,'video');//保存错误删除刚刚上传的文件
throw new APIException('添加视频信息出错',-13);
}
}
<h5>ossService</h5>
ossService分装了上传和删除方法
<?php namespace App\Services;
use App\Lib\Curl;
use Sky\Lib\APIException;
use Sky\Lib\Cache;
use Sky\Lib\Config;
use Sky\Lib\Log;
use App\Lib\Util;
use OSS\OssClient;
use OSS\Core\OssException;
class OssService
{
static $ossConfig;
/**
* 根据Config配置,得到一个OssClient实例
* @return OssClient 一个OssClient实例
*/
static function getOssClient($type)
{
//根据类型获取配置
self::$ossConfig=Config::get('alioss')[$type];
try {
$ossClient = new \OSS\OssClient(self::$ossConfig['oss_key'],self::$ossConfig['oss_secret'],self::$ossConfig['oss_endpoint'],false);
} catch ( OSS\Core\OssException $e) {
throw new APIException('连接Oss存储失败,错误信息:'.$e->getMessage(),-2);
}
return $ossClient;
}
/**
* @Description 写入文件
* @Author Depp
* @DateTime 2020-03-25
* @param [type] $path [description]
* @param [type] $resource [description]
* @param Config $config [description]
* @return [type] [description]
*/
static function writeStream($saveName,$filePath,$type)
{
$ossClient=self::getOssClient($type);
$oss_path=ltrim($saveName,'./');
try {
$result = $ossClient->uploadFile(self::$ossConfig['oss_bucket'], $oss_path, $filePath);
} catch (OSS\Core\OssException $e) {
throw new APIException('上传文件失败,错误信息:'.$e->getMessage(),-2);
}
return self::get_url($saveName);
}
/**
* @Description 删除文件
* @Author Depp
* @DateTime 2020-03-27
* @param [type] $fileName [阿里云存储路径 例:video/20200327/4bd9f4ade08ae7a3.mp4]
* @param [type] $type [description]
* @return [type] [description]
*/
static function deleteStream($fileName,$type){
$ossClient=self::getOssClient($type);
$object=ltrim($fileName,'./');
try {
$res=$ossClient->deleteObject(self::$ossConfig['oss_bucket'],$object);
} catch (OSS\Core\OssException $e) {
throw new APIException('删除文件失败,错误信息:'.$e->getMessage(),-2);
}
}
/**
* 获取完整网络连接
* @param string $path 文件路径
* @return string http连接
*/
static function get_url($path){
// 如果是空;返回空
if (empty($path)) {
return '';
}
// 如果已经有http直接返回
if (strpos($path, 'http://')!==false) {
return $path;
}
// 获取bucket
return 'http://'.self::$ossConfig['oss_bucket'].'.oss-cn-beijing.aliyuncs.com'.$path;
}
}
<h5>其他</h5>
Oss对象存储并不只有上传和删除这两个方法,还包括修改、分片传输、查看backet等好多方法,我只不过就简单实现了上传和删除这两个方法,大家有需要的可以自己查找一下。