图片上传阿里云oss

1、composer加载oss插件

composer require aliyuncs/oss-sdk-php

2、更改config配置

//控制器代码如下

 public function aliyun($category='',$isunlink=false,$bucket="phpchai"){
        $file=$_FILES;
        $savePath=$file['file']['name'];//文件名称
        $accessKeyId = config('aliyun_oss.accessKeyId');//去阿里云后台获取秘钥
        $accessKeySecret = config('aliyun_oss.accessKeySecret');//去阿里云后台获取秘钥
        $endpoint = config('aliyun_oss.endpoint');//你的阿里云OSS地址
        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
        //   判断bucketname是否存在,不存在就去创建
        if( !$ossClient->doesBucketExist($bucket)){
            $ossClient->createBucket($bucket);
        }
        $category=empty($category)?$bucket:$category;
        $object = $category.'/'.$savePath;//想要保存文件的名称
        $file = 'E:/img/'.$savePath;//文件路径,必须是本地的。
        try{
            $ossClient->uploadFile($bucket,$object,$file);
            if ($isunlink==true){
                unlink($file);
            }
        }catch (OssException $e){
            $e->getErrorMessage();
        }
        $oss=config('aliyun_oss.url');
        $img=$oss.$object;
      //  $this->addShop($img);
        return $oss.$object;
    }

猜你喜欢

转载自www.cnblogs.com/chaihtml/p/12083631.html