Laravel框架 将 【图片上传到腾讯云COS】 和 【从腾讯云COS上删除图片】

前言:

       其实我也是看的别人的,整理出一套自己可以直接使用的代码和开发步骤,我可以用,不代表你可以用,所以如果不能用请自己爬坑。 

配置:

  在 composer.json 文件的 require  中  添加 一句  :

 "caojianfei/laravel-qcloud-cos": "^1.0"

然后执行命令:更新一下依赖 

composer update 

修改一下:config\filesystems.php 文件: (直接替换就可以)

 env('FILESYSTEM_DRIVER', 'qcloud-cos'),

    /*
    |--------------------------------------------------------------------------
    | Default Cloud Filesystem Disk
    |--------------------------------------------------------------------------
    |
    | Many applications store files both locally and in the cloud. For this
    | reason, you may specify a default "cloud" driver here. This driver
    | will be bound as the Cloud disk implementation in the container.
    |
    */

    'cloud' => env('FILESYSTEM_CLOUD', 's3'),

    /*
    |--------------------------------------------------------------------------
    | Filesystem Disks
    |--------------------------------------------------------------------------
    |
    | Here you may configure as many filesystem "disks" as you wish, and you
    | may even configure multiple disks of the same driver. Defaults have
    | been setup for each driver as an example of the required options.
    |
    | Supported Drivers: "local", "ftp", "sftp", "s3", "rackspace"
    |
    */

    'disks' => [

        'local' => [
            'driver' => 'local',
            'root' => storage_path('app'),
        ],

        'public' => [
            'driver' => 'local',
            'root' => storage_path('app/public'),
            'url' => env('APP_URL').'/storage',
            'visibility' => 'public',
        ],

        's3' => [
            'driver' => 's3',
            'key' => env('AWS_ACCESS_KEY_ID'),
            'secret' => env('AWS_SECRET_ACCESS_KEY'),
            'region' => env('AWS_DEFAULT_REGION'),
            'bucket' => env('AWS_BUCKET'),
            'url' => env('AWS_URL'),
        ],
        //腾讯云存储
        'qcloud-cos' => [
            'driver' => 'qcloud-cos',
            'region' => env('COS_REGION', 'cd-chengdu'),
            'credentials' => [
                'app_id' =>  env('COS_APPID'),
                'secret_id' =>  env('COS_SECRET_ID'),
                'secret_key' => env('COS_SECRET_KEY'),
                'token' => env('QCLOUD_COS_TOKEN', null)
            ],
            'default_bucket' =>  env('COS_BUCKET'),
            'timeout' => env('QCLOUD_COS_TIMEOUT', 3600),
            'connect_timeout' =>  env('QCLOUD_COS_CONNECT_TIMEOUT', 3600)
        ],

    ],

];

在.env文件中添加的COS腾讯云连接配置: 


COS_APPID=1252495372
COS_SECRET_ID=AKIDP95CW3B2Gc6fSQz2gRIErgtHzplnKr6W
COS_SECRET_KEY=ppv7TnElQGDGXyeQ5qkp0ZOKOdxDa4kc
COS_REGION=cd
COS_BUCKET=article-power
COS_BASE_URL=http://article-power-1252495372.coscd.myqcloud.com/

DEFAULT_IMAGE = apiUpload/kegfsCAD3ikxDjYzgdUj6bKJlpv35rw5Si9HFMur.png

清一下缓存: 

php artisan config:clear

 

提交图片 和 删除 图片的  代码 :

(1)路由: 

Route::post('upload_file', 'Api\HelperController@upload_file')->name('upload_file');//上传图片
Route::post('delete_file', 'Api\HelperController@delete_file')->name('delete_file');//删除图片

(2)控制器:

validate([
            'file' => 'required|image',
        ]);
        try{
            $file = $request->file;
            if($file->isValid()){
                $res = Media::uploadFile("apiUpload",$file);
                return $this->success($res);
            }
        }catch(\Exception $e){
            return $this->error($e);
        }
        return $this->error("上传失败");
    }
    /**
     * @SWG\Get(
     *     path="/delete_file",
     *     summary="删除COS文件",
     *     tags={"公共"},
     *     @SWG\Parameter(name="url",type="integer",description ="文件url",in="query"),
     *     @SWG\Response(response=200,description="返回成功")
     * )
     */
    public function delete_file(Request $request){
        $request->validate([
            'url' => 'required',
        ]);
        $res = Media::delImage($request->url);
        return $res["error"]==0?$this->success($res["msg"]):$this->error($res["msg"]);
    }

}

(3)门面:

getClientOriginalExtension();


        if($folder=="music"){
            if(!in_array($extension, ["mp3","wma","mpga"])){
                return ['error'=>'1', 'msg'=>'音乐类型需要是mp3,wma,mpga.'];
            }
        }else if (!in_array($extension, ["png", "jpg", "gif"])) {
            return ['error'=>'1', 'msg'=>'图片类型需要是png, jpg 或者 gif.'];
        }
        $result = $file->store($folder);
        if($result){
            return [
                'error'=>0,
                'msg'=>'上传成功!',
                'data'=>[
                    'url'=>$result,
                    'base_url'=>env("COS_BASE_URL")
                ]
            ];
        }
        return ['error'=>'1', 'msg'=>'你自己找错吧!'];
    }

    //图片删除
    public static function delImage($image_url)
    {
        if($image_url == null){
            return ['error'=>'0', 'msg'=>'执行成功'];
        }
        $result = null;
        try{
            $result=Storage::delete($image_url);
            return $result?['error'=>'0', 'msg'=>"删除成功!"]:['error'=>'1', 'msg'=>"未找到文件!"];
        }catch(Exception $e){}
        return ['error'=>'1', 'msg'=>'你自己找错吧!'];
    }
}

 

你可能感兴趣的:(Laravel框架)