1.先用composer安裝阿里雲OSS的PHPSDK
2.配置文件里定義阿里雲OSS的秘鑰
3.在index控制器里的代碼封裝
<?php namespace app\index\controller; use OSS\OssClient; use OSS\Core\OssException; use OSS\Core\OssUtil; use think\Config; class Index extends Base { // 阿里OSS相關參數 protected $accessKeyId = ''; protected $accessKeySecret = ''; protected $endpoint = ''; protected $bucket = ''; // 文件上傳相關設置 protected $image_size = 0; protected $video_size = 0; protected $other_size = 0; /** * 構造函數 */ public function _initialize() { $this->accessKeyId = Config::get('aliyun_oss')['accessKeyId']; $this->accessKeySecret = Config::get('aliyun_oss')['accessKeySecret']; $this->endpoint = Config::get('aliyun_oss')['endpoint']; $this->bucket = Config::get('aliyun_oss')['bucket']; $this->image_size = Config::get('upload_set')['image_size']; $this->video_size = Config::get('upload_set')['video_size']; $this->other_size = Config::get('upload_set')['other_size']; } /** * 測試頁面 */ public function index() { return $this->fetch(); } /** * 創建存儲空間 */ public function createBucket() { if (!request()->isPost()) { throw new \think\Exception('請求方式錯誤!'); } $bucket = input('param.bucket'); if (empty($bucket)) { return json(['data' => '', 'code' => 1, 'message' => '存儲空間名不能為空!']); } try { $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint); $ossClient->createBucket($bucket); return json(['data' => '', 'code' => 0, 'message' => $bucket . '存儲空間創建成功']); } catch (OssException $e) { return json(['data' => $e->getMessage(), 'code' => 1, 'message' => '創建失敗']); } } /** * 上傳文件 */ public function uploadFile() { /*判斷提交方式*/ if (!request()->isPost()) { throw new \think\Exception('請求方式錯誤!'); } /*獲取到上傳的文件*/ $file = $_FILES['file']; if (!$file) { return json(['data' => '', 'code' => 1, 'message' => '文件不存在!']); } // 判斷文件大小 if ($file['size'] > $this->other_size) { return json(['data' => '', 'code' => 1, 'message' => '文件大小不能超過' . ($this->other_size / 1024 / 1024) . 'M']); } $name = $file['name']; $format = strrchr($name, '.');//截取文件后綴名如 (.jpg) /*判斷圖片格式*/ $allow_type = ['.zip', '.rar', '.doc','.docx','xls','xlsx','mp3','wav']; if (!in_array($format, $allow_type)) { return json(['data' => '', 'code' => 1, 'message' => '文件格式不在允許范圍內']); } // 嘗試執行 try { //實例化對象 將配置傳入 $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint); //這里是有sha1加密 生成文件名 之后連接上后綴 $fileName = 'upload/file/' . date("Ymd") . '/' . sha1(date('YmdHis', time()) . uniqid()) . $format; //執行阿里雲上傳 $result = $ossClient->uploadFile($this->bucket, $fileName, $file['tmp_name']); /*組合返回數據*/ $arr = [ 'oss_url' => $result['info']['url'], //上傳資源地址 'relative_path' => $fileName //數據庫保存名稱(相對路徑) ]; } catch (OssException $e) { return json(['data' => $e->getMessage(), 'code' => 1, 'message' => '上傳失敗!']); } //將結果返回 return json(['data' => array('file' => $arr['oss_url']), 'code' => 0, 'message' => '成功上傳到oss']); } /** * 上傳視頻 */ public function uploadVideo() { /*判斷提交方式*/ if (!request()->isPost()) { throw new \think\Exception('請求方式錯誤!'); } /*獲取到上傳的文件*/ $file = $_FILES['file']; if (!$file) { return json(['data' => '', 'code' => 1, 'message' => '文件不存在!']); } // 判斷文件大小 if ($file['size'] > $this->video_size) { return json(['data' => '', 'code' => 1, 'message' => '視頻大小不能超過' . ($this->video_size / 1024 / 1024) . 'M']); } $name = $file['name']; $format = strrchr($name, '.');//截取文件后綴名如 (.jpg) /*判斷圖片格式*/ $allow_type = ['.mp4', '.avi', '.rmvb']; if (!in_array($format, $allow_type)) { return json(['data' => '', 'code' => 1, 'message' => '視頻格式不在允許范圍內']); } // 嘗試執行 try { //實例化對象 將配置傳入 $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint); //這里是有sha1加密 生成文件名 之后連接上后綴 $fileName = 'upload/video/' . date("Ymd") . '/' . sha1(date('YmdHis', time()) . uniqid()) . $format; //執行阿里雲上傳 $result = $ossClient->uploadFile($this->bucket, $fileName, $file['tmp_name']); /*組合返回數據*/ $arr = [ 'oss_url' => $result['info']['url'], //上傳資源地址 'relative_path' => $fileName //數據庫保存名稱(相對路徑) ]; } catch (OssException $e) { return json(['data' => $e->getMessage(), 'code' => 1, 'message' => '上傳失敗!']); } //將結果返回 return json(['data' => array('file' => $arr['oss_url']), 'code' => 0, 'message' => '成功上傳到oss']); } /** * 上傳圖片 */ public function uploadImage() { /*判斷提交方式*/ if (!request()->isPost()) { throw new \think\Exception('請求方式錯誤!'); } /*獲取到上傳的文件*/ $file = $_FILES['file']; if (!$file) { return json(['data' => '', 'code' => 1, 'message' => '文件不存在!']); } // 判斷文件大小 if ($file['size'] > $this->image_size) { return json(['data' => '', 'code' => 1, 'message' => '視頻大小不能超過' . ($this->image_size / 1024 / 1024) . 'M']); } $name = $file['name']; $format = strrchr($name, '.');//截取文件后綴名如 (.jpg) /*判斷圖片格式*/ $allow_type = ['.jpg', '.jpeg', '.gif', '.bmp', '.png']; if (!in_array($format, $allow_type)) { return json(['data' => '', 'code' => 1, 'message' => '圖片格式不在允許范圍內']); } // 嘗試執行 try { //實例化對象 將配置傳入 $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint); //這里是有sha1加密 生成文件名 之后連接上后綴 $fileName = 'upload/image/' . date("Ymd") . '/' . sha1(date('YmdHis', time()) . uniqid()) . $format; //執行阿里雲上傳 $result = $ossClient->uploadFile($this->bucket, $fileName, $file['tmp_name']); /*組合返回數據*/ $arr = [ 'oss_url' => $result['info']['url'], //上傳資源地址 'relative_path' => $fileName //數據庫保存名稱(相對路徑) ]; } catch (OssException $e) { return json(['data' => $e->getMessage(), 'code' => 1, 'message' => '上傳失敗!']); } //將結果返回 return json(['data' => array('file' => $arr['oss_url']), 'code' => 0, 'message' => '成功上傳到oss']); } /** * 上傳圖片base64 */ public function uploadImageBase64() { // 判斷提交方式及圖片類型 if (!request()->has('base64', 'post')) { return json(['data' => '', 'code' => 1, 'message' => '請求方式錯誤,或圖片非base64格式類型']); } $data = $_POST['base64']; $result = $this->new_base64_upload($data); if ($result['code'] !== 200) { return json(['data' => '', 'code' => 1, 'message' => $result['msg']]); } $fileResult = &$result['data']; $filePath = $fileResult['path'] . $fileResult['name']; $ossFileName = implode('/', ['upload/image', date('Ymd'), $fileResult['name']]); try { //實例化對象 將配置傳入 $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint); $result = $ossClient->uploadFile($this->bucket, $ossFileName, $filePath); $arr = [ 'oss_url' => $result['info']['url'], //上傳資源地址 'relative_path' => $ossFileName //數據庫保存名稱(相對路徑) ]; } catch (OssException $e) { return json(['data' => $e->getMessage(), 'code' => 1, 'message' => '上傳失敗']); } unlink($filePath); return json(['data' => array('file' => $arr['oss_url']), 'code' => 0, 'message' => '成功上傳到oss']); } /** * 將Base64數據轉換成二進制並存儲到指定路徑 */ protected function new_base64_upload($base64, $image_path = 'upload/posts/') { $data = explode(',', $base64); trace($data, 'api'); unset($base64); if (count($data) !== 2) { return ['code' => 400, 'msg' => '文件格式錯誤']; } if (!preg_match('/^(data:\s*image\/(\w+);base64)/', $data[0], $result)) { return ['code' => 400, 'msg' => '文件格式錯誤']; } $type = $result[2]; if (!in_array($type, array('jpeg', 'jpg', 'gif', 'bmp', 'png'))) { return ['code' => 400, 'msg' => '文件格式不在允許范圍內']; } $image_name = md5(uniqid()) . '.' . $result[2]; $image_file = $image_path . $image_name; //服務器文件存儲路徑 try { if (file_put_contents($image_file, base64_decode($data[1]))) { return ['code' => 200, 'msg' => '成功', 'data' => ['name' => $image_name, 'path' => $image_path]]; } else { return ['code' => 400, 'msg' => '文件保存失敗']; } } catch (\Exception $e) { $msg = $e->getMessage(); return ['code' => 400, 'msg' => $msg]; } } }