天天看點

tp5使用oss存儲圖檔

1.申請Access Key ID和Access Key Secret,以及建立好你的Bucket

2.通過composer安裝oss插件

通過cmd,到項目的目錄下,輸入下面的指令。
composer require aliyuncs/oss-sdk-php
           

3.配置好oss資訊,在config.php中

'aliyun_oss' => [
        'accessKeyId'      => '',  //您的Access Key ID
        'accessKeySecret'  => '',  //您的Access Key Secret
        'endpoint'   => '',  //阿裡雲oss 外網位址endpoint
        'bucket'     => '',  //Bucket名稱
        'url'           => ''  // 通路的位址
]
           

4.上傳圖檔,并處理到aliyun中

function aliyun($savePath,$category='',$isunlink=false,$bucket="yunlutong-img"){
        $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;

        $savePath = str_replace("\\","/",$savePath);

        $object = $category.'/'.$savePath;//想要儲存檔案的名稱
        $file = './uploads\\'.$savePath;//檔案路徑,必須是本地的。

        try{
            $ossClient->uploadFile($bucket,$object,$file);
            if ($isunlink==true){
                unlink($file);
            }
        }catch (OssException $e){
            $e->getErrorMessage();
        }
        $oss=config('aliyun_oss.url');
        return $oss."/".$object;
}

           

記得要在類的頭部引入,

use \OSS\OssClient;
           

在圖檔長傳之後,處理到阿裡雲oss中,并将位址儲存到資料庫

// 添加
$file = request()->file('img');

// 移動到架構應用根目錄/public/uploads/ 目錄下
$upload_info = $file->move(config('upload_path'));
if(!$upload_info){
    // 上傳失敗擷取錯誤資訊
    $this->error($file->getError());
}

$oss_img_url = $this->aliyun($upload_info->getSaveName(),'live');

$data['title'] = input('post.title');
$data['info'] = input('post.info');
$data['url'] = input('post.url');
$data['sort'] = input('post.sort');
$data['addtime'] = time();
$data['img'] = $oss_img_url;// '/uploads\\'.$upload_info->getSaveName();

$res = db("live_banner")->insert($data);
if ($res) {
    $this->success('操作成功', url('LiveExtra/bannerList'));
} else {
    $this->error('操作失敗');
}
           
tp5使用oss存儲圖檔