原地址:https://help.aliyun.com/document_detail/88473.html?spm=a2c4g.11186623.6.1090.316c145eysHW9d
方法封裝:
public function uploads(Request $request) { $pictrue = ''; // 獲取圖片轉base64的字符串 $result = []; // 轉化base64編碼圖片 jpeg、jpg、png、bmp、gif if(preg_match('/^(data:\s*image\/(\w+);base64,)/', $pictrue, $result)) { $type = $result[2]; // 獲取圖片類型 if(in_array($type, array('pjpeg','jpeg','jpg','bmp','png'))) { // 圖片名字 $fileName = time().rand(1,1000).'.'.$type; // 圖片名稱 // 臨時文件 $tmpfname = tempname("./image/", "FOO"); // windows $tmpfname = ('/tmp/', 'FOO'); // linux // 保存圖片 $handle = fopen($tmpfname, "w"); // return [$pic, $result]; $object = 'school/avatar/'.date('Y/m/d').'/'.$fileName; // 阿里雲上傳地址 if (fwrite($handle, base64_decode(str_replace($result[1], '', $pic)))) { // 上傳圖片至阿里雲OSS $ossClient = new Aliyunoss(); $data = $ossClient->uploads($object, $tmpfname); // return [$pic, $result, $data]; // 關閉緩存 fclose($handle); // 刪除本地該圖片 unlink($tmpfname); // 返回圖片鏈接 return StatusCode::getCode(0, ['data' => $data]); }else { return response(['message'=>'圖片上傳失敗'], 200); } }else { return response(['message'=>'圖片類型錯誤'], 200); } } else { return response(['message'=>'圖片編碼錯誤'], 200); } }
阿里雲OSS
public function uploads($object, $content) { $ossClient = self::getOssClient(); if (is_null($ossClient)) exit(1); $bucket = self::getBucketName(); try{ $ossClient->uploadFile($bucket, $object, $content); } catch(OssException $e) { self::println(__FUNCTION__ . ": FAILED\n"); self::println($e->getMessage() . "\n"); $object = 'error'; } return $object; }