上傳圖片到七牛雲(tp5)
阿新 • • 發佈:2019-01-03
前期準備:
1.註冊七牛雲配置相關引數(參考七牛雲官網)
2.將七牛雲 sdk 根據七牛官網整合到tp5中
程式碼部分:
配置檔案(在config中)
[ 'accessKey'=>'', 'secretKey'=>'', 'bucket'=>'',//上傳空間名稱 'DOMAIN'=>''//空間繫結的域名 ]
/** *上傳圖片 */ public function test(){ //獲取圖片 $photo = $this->request->file('photo'); //處理圖片 $filepath = $photo->getRealPath();//檔案路徑 $info['photo']=self::photoName($photo);// 獲取處理後圖片的名稱 //呼叫方法上傳 $img =self::upload($info['photo'],$filepath); //判斷返回資訊 如果是0 則返回錯誤資訊 if($img['err'] !== 0 ){ $this->error($img['msg']); } /** * tp5七牛雲上傳檔案 * */ public function upload($key,$filePath){ //引入autoload.php檔案 require_once APP_PATH . '/../vendor/Qiniu/autoload.php'; // 需要填寫你的 Access Key 和 Secret Key $accessKey = config('qiniu.accessKey'); $secretKey = config('qiniu.secretKey'); // 構建鑑權物件 $auth = new Auth($accessKey, $secretKey); // 要上傳的空間 $bucket = config('qiniu.bucket'); $domain = config('qiniu.DOMAIN'); $token = $auth->uploadToken($bucket); // 初始化 UploadManager 物件並進行檔案的上傳 $uploadMgr = new UploadManager(); // 呼叫 UploadManager 的 putFile 方法進行檔案的上傳 $token 上傳憑證 $key 上傳檔名 $filepath 上傳檔案的路徑 list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath); if ($err !== null) { return ["err"=>1,"msg"=>$err,"data"=>""]; } else {//成功 //返回圖片的完整URL return ["err"=>0,"msg"=>"上傳完成","data"=>($domain .'/'. $ret['key'])]; } }
/** * 獲取名字 */ function photoName($file){ $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION); //字尾 $result =substr(md5($file->getRealPath()) , 0, 5). date('YmdHis') . rand(0, 9999) . '.' . $ext; return $result; }