tp5封装aliyun oss上传类

 首先下载阿里云的oss php sdk包 到 tp5的 vendor目录里

包地址:https://github.com/aliyun/aliyun-oss-php-sdk/releases?spm=a2c4g.11186623.2.16.4bc7c8393RRxsJ

然后封装操作oss类

bucket = 'aliyun-oss';
        try {
            $this->ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
            // 设置存储空间的存储类型为低频访问类型,默认是标准类型。
            $options = array(
                OssClient::OSS_STORAGE => OssClient::OSS_STORAGE_IA
            );
        } catch (OssException $e) {
            out_err('阿里云oss链接失败'.$e->getMessage());
        }
    }

    // 获取 bucket 列表
    public function getYunOssBucketList(){
        $ossClient = $this->ossClient;
        try{
            $bucketListInfo = $ossClient->listBuckets();
        } catch(OssException $e) {
            printf(__FUNCTION__ . ": FAILED
"); printf($e->getMessage() . "
"); return; } $bucketList = $bucketListInfo->getBucketList(); foreach($bucketList as $bucket) { print($bucket->getLocation() . "\t" . $bucket->getName() . "\t" . $bucket->getCreatedate() . "
" ); } } //获取 bucket 权限 public function getYunOssBucketAuthor(){ $ossClient = $this->ossClient; // 存储空间名称。 $bucket= "aliyun-oss"; try { $res = $ossClient->getBucketAcl($bucket); } catch (OssException $e) { printf(__FUNCTION__ . ": FAILED
"); printf($e->getMessage() . "
"); return; } print(__FUNCTION__ . ": OK" . "
"); print('acl: ' . $res); } //获取 bucket 文件列表 public function getYunOssBucketFileList(){ $ossClient = $this->ossClient; // 存储空间名称。 $bucket= "aliyun-oss"; $prefix = 'users/2018/08-29/'; $delimiter = '/'; $nextMarker = ''; $maxkeys = 10; $options = array( 'delimiter' => $delimiter, 'prefix' => $prefix, 'max-keys' => $maxkeys, 'marker' => $nextMarker, ); try { $listObjectInfo = $ossClient->listObjects($bucket, $options); } catch (OssException $e) { printf(__FUNCTION__ . ": FAILED
"); printf($e->getMessage() . "
"); return; } print(__FUNCTION__ . ": OK" . "
"); $objectList = $listObjectInfo->getObjectList(); // object list $prefixList = $listObjectInfo->getPrefixList(); // directory list if (!empty($objectList)) { print("objectList:
"); foreach ($objectList as $objectInfo) { print($objectInfo->getKey() . "
"); } } if (!empty($prefixList)) { print("prefixList:
"); foreach ($prefixList as $prefixInfo) { print($prefixInfo->getPrefix() . "
"); } } } //获取 bucket 文件权限 public function getYunOssBucketFileAuthor(){ if(IS_POST && !empty($_POST)) { $ossClient = $this->ossClient; // 存储空间名称。 $bucket = "aliyun-oss"; //包含路径和后缀 的文件名 $object = input('param.files'); try { $objectAcl = $ossClient->getObjectAcl($bucket, $object); } catch (OssException $e) { printf(__FUNCTION__ . ": FAILED\n"); printf($e->getMessage() . "\n"); return; } print(__FUNCTION__ . ": OK" . "\n"); var_dump($objectAcl); } return view('api@/read-ossfileauthor'); } //设置 bucket 文件权限 public function setYunOssBucketFileAuthor(){ if(IS_POST && !empty($_POST)) { $ossClient = $this->ossClient; // 存储空间名称。 $bucket = "aliyun-oss"; //包含路径和后缀 的文件名 $object = input('param.files'); // 设置文件的访问权限,默认为继承Bucket。 //继承Bucket 文件遵循存储空间的访问权限。 default //私有 文件的拥有者和授权用户有该文件的读写权限,其他用户没有权限操作该文件。 private //公共读 文件的拥有者和授权用户有该文件的读写权限,其他用户只有文件的读权限。请谨慎使用该权限。 public-read //公共读写 所有用户都有该文件的读写权限。请谨慎使用该权限。 public-read-write $acl = input('param.author'); try { $ossClient->putObjectAcl($bucket, $object, $acl); } catch (OssException $e) { printf(__FUNCTION__ . ": FAILED\n"); printf($e->getMessage() . "\n"); return; } print(__FUNCTION__ . ": OK" . "\n"); } return view('api@/set-ossfileauthor'); } //上传单个文件 public function doYunOssBucketUploadFileSample(){ if(IS_POST && !empty($_FILES)){ $ossClient = $this->ossClient; // 存储空间名称。 $bucket= "aliyun-oss"; $path = 'test/'; //上传到服务器的路径 // 文件名称, 即上传到服务器的 路径 + 名称 $object = $path.$_FILES['files']['name']; // 由本地文件路径加文件名包括后缀组成,例如/users/local/myfile.txt $filePath = $_FILES['files']['tmp_name']; try{ $ossClient->uploadFile($bucket, $object, $filePath); } catch(OssException $e) { printf(__FUNCTION__ . ": FAILED
"); printf($e->getMessage() . "
"); return; } print(__FUNCTION__ . ": OK" . "
"); echo '
'; echo '
'; echo '
'; } return view('api@/ossuploadsample'); } /** * @description 上传多个文件 * 例如 * doYunOssBucketUploadFileMultiple('test/',$_FILES['files'],['5913.mp4'=>'1.mp4','5914.mp4'=>'2.mp4']); * @param $filepath string 上传到oss的文件夹路径 例如 'test/' * @param $file array 上传的文件,直接传 $_FILES['files'] * @param $type string 允许上传的文件类型 例如 image video * @param $size int 允许上传的文件大小 例如 10485760 * @return 结果数组 Array() * array(2) { [0] => array(3) { ["code"] => int(1) ["file"] => string(8) "http://zhj-oss.oss-cn-shenzhen.aliyuncs.com/test/1.mp4" ["msg"] => string(6) "成功" } [1] => array(3) { ["code"] => int(-1) ["file"] => string(8) "5914.mp4" ["msg"] => string(6) "失败" } } * @author guilong * @date 2018-09-01 */ public function doYunOssBucketUploadFileMultiple($filepath = '',$file = [],$type = 'image',$size = 10485760 ){ $return = []; $file_type = [ 'image' => 'image/gif,image/x-png,image/pjpeg,image/jpeg,image/bmp,image/png,image/jpg', 'video' => 'application/octet-stream,video/mp4,video/ogg,video/webm', ]; if($file){ if(!is_array($file['tmp_name'])){ foreach($file as $k => $v){ $file[$k] = array($v); } } $ossClient = $this->ossClient; // 存储空间名称。 $bucket= $this->bucket; $path = $filepath; //上传到服务器的路径 foreach($file['tmp_name'] as $k => $v) { $starttime = microtime(true); //开始时间 $ext = explode('.',$file['name'][$k]); $file_name = md5($starttime).mt_rand(100,999).mt_rand(1000,9999).'.'.$ext[count($ext)-1]; //文件名称 ,包含后缀 $newFilename = !empty($file_name) ? $file_name : $file['name'][$k]; // 文件名称 , 即上传到服务器的 路径 + 名称 $object = $path . $newFilename; // 由本地文件路径加文件名包括后缀组成,例如/users/local/myfile.txt $filePath = $v; try { // if(isset($file_type[$type]) && stripos($file_type[$type],strtolower($file['type'][$k])) === false){ //文件类型不符合 ,判断文件类型 if(isset($file_type[$type]) && stripos($file_type[$type],strtolower($ext[count($ext)-1])) === false){ //文件类型不符合 ,直接判断后缀 $data = [ 'code' => -1, 'file' => $file['name'][$k], 'msg' => '文件类型不符合', ]; }else if($file['size'][$k] > $size){ //文件超出限制大小 $data = [ 'code' => -1, 'file' => $file['name'][$k], 'msg' => '文件超出限制大小', ]; }else{ $result = $ossClient->uploadFile($bucket, $object, $filePath); //把oss域名 替换成 $cdn_domain $image_array = explode(',',$result['info']['url']); $image_array2 = imgCdnReplace($image_array); $str = $image_array2[0]; $data = [ 'code' => 1, 'file' => $result['info']['url'], //返回文件上传后的oss目录 'cdn_file' => $str, //返回文件上传后的cdn目录 //snapshot,t_1000,m_fast,w_218,h_260 //截取视频的第一秒 , 固定宽度 218 固定高度 260 'cdn_file_screenshot' => $type == 'video' ? $str.'?x-oss-process=video/snapshot,t_1000,m_fast,w_218,h_260' : '', //返回文件上传视频后的截图 'msg' => '上传成功', ]; } } catch (OssException $e) { $data = [ 'code' => -1, 'file' => $file['name'][$k], //返回文件名称 'msg' => $e->getMessage() , ]; } $return[] = $data; } }else{ $return[] = [ 'code' => -1, 'file' => '', 'msg' => '请选择上传文件', ]; } return $return; } //删除文件 public function doYunOssBucketDeleteFile(){ if(IS_POST && !empty($_POST)){ $ossClient = $this->ossClient; // 存储空间名称。 $bucket= "aliyun-oss"; //包含路径和后缀 的文件名 $files = input('param.files'); try{ $ossClient->deleteObject($bucket, $files); } catch(OssException $e) { printf($files . ": 删除失败
"); printf($e->getMessage() . "
"); return; } print($files . ": 删除成功" . "
"); echo '
'; echo '
'; echo '
'; } return view('api@/ossfiledelete'); } }

 

调用:

//上传到阿里云oss
$aliyunoss = new AliyunOss();
$path = 'image/'.date('Y').'/'.date('m-d').'/';
$ossres = $aliyunoss->doYunOssBucketUploadFileMultiple($path,$_FILES['headimg'],'image');
if($ossres[0]['code'] == 1){ //上传成功
    $headimg = $ossres[0]['file'];
    $cdn_headimg = $ossres[0]['cdn_file'];
}else if($ossres[0]['code'] == -1){ //上传失败
    echo '上传失败';
    exit;
}

 

你可能感兴趣的:(php,aliyunoss)