上传到腾讯云储存 2020-09-03 16:15:55

一、安装扩展包

composer require freyo/flysystem-qcloud-cos-v5

二、修改配置文件

# config/app.php

'providers' => [
  // ...
  Freyo\Flysystem\QcloudCOSv5\ServiceProvider::class,
]

# config/filesystems.php

'disks' => [
    // ...
    'cosv5' => [
        'driver' => 'cosv5',
        'region' => env('COSV5_REGION', 'ap-beijing'),//后面是控制台储存桶里设置的所属地域
        'credentials'  => [
            'appId' => env('COSV5_APP_ID'),
            'secretId' => env('COSV5_SECRET_ID'),
            'secretKey' => env('COSV5_SECRET_KEY'),
        ],
        'timeout' => env('COSV5_TIMEOUT', 60),
        'connect_timeout' => env('COSV5_CONNECT_TIMEOUT', 60),
        'bucket' => env('COSV5_BUCKET'),
        'cdn' => env('COSV5_CDN'),
        'scheme' => env('COSV5_SCHEME', 'https'),
        'read_from_cdn' => env('COSV5_READ_FROM_CDN', false),
    ],
]

三、配置.env

COSV5_APP_ID= ##APPid
COSV5_SECRET_ID=  ##APP_secret
COSV5_SECRET_KEY=  ## APP_KEY
COSV5_TIMEOUT=60
COSV5_CONNECT_TIMEOUT=60
COSV5_BUCKET= ##存储桶
COSV5_REGION=ap-beijing ##地区
COSV5_CDN= ##访问域名
COSV5_SCHEME=https
COSV5_READ_FROM_CDN=false

四、PHP代码

// 文件储存对象
use Illuminate\Support\Facades\Storage;

// 上传
public function up(Request $request)
{
        $file = $request->file('name');
        $disk = Storage::disk('cosv5');
        //第一个参数是你储存桶里想要放置文件的路径,第二个参数是文件对象
        $file_content = $disk -> put('储存桶文件夹名',$file);
        $file_url = $disk->url($file_content);//获取到文件的线上地址
}

// 删除
public function del()
{
        $url = 'https://文件访问地址';
        # 正则,从地址中提取文件名,并存入$res
        preg_match("/https:\/\/(.+?)com\//", $url, $res);
        $file_urs = str_replace($res[0],"",$url);
        $arr = array();
        # 将要删除的文件存入数组(可多个)
        array_push($arr, $file_urs);
        try {
                $disk = Storage::disk('cosv5');
                $file_content = $disk->delete($arr);
        } catch (\Exception $e) {
                //请求失败
                echo($e);
        }
}

 

  1. Laravel5.7
  2. 微信相关
  3. Mysql
  4. 前端开发
  5. 随记
  6. 写作素材
  7. 开发工具
  8. 互联网