1. 程式人生 > >php/PHP 阿里雲OSS檔案上傳

php/PHP 阿里雲OSS檔案上傳

 一、封裝的upload方法能看懂就看 看不懂直接使用 

       1.支援base64和普通表單等檔案上傳方式(會自動判斷方式)

        2.呼叫時候只需要傳入一個要上傳到阿里雲的地址即可

        3.返回結果是個json物件 示例如下:

           path:返回上傳成功後oss圖片地址.

{
  "code": 200,
  "msg": "成功",
  "data": {
    "path": "http://xzfct.oss-cn-beijing.aliyuncs.com/upload/wechat/20180927/a848dc251ae60074ad233babaa711e7c.jpeg"
  }
}
 /**
     * 阿里雲OSS圖片上傳
     * @$ossUploadPath,設定要上傳到oss的某個目錄
     * @return array
     */
    public function upload($ossUploadPath = 'upload/image'){
        // if(Request::has($base64Key,'post')){
        if($_POST){
            foreach($_POST as $base64Image){
                $result = $this->base64_upload($base64Image);
                if ($result['code'] === RENDER_CODE_SUCCESS){
                    $fileResult = &$result['data'];
                    $filePath = $fileResult['path'] . $fileResult['name'];
                    $ossFileName = implode('/', [$ossUploadPath,date('Ymd'),$fileResult['name']]);
                    try {
                        $config = config('api.aliyun_oss');
                        $ossClient = new OssClient($config['key_id'], $config['key_secret'], $config['endpoint']);
                        $result = $ossClient->uploadFile($config['bucket'], $ossFileName, $filePath);
                        /*組合返回資料*/
                        $arr = [
                            'oss_url' => $result['info']['url'],  //上傳成功後返回的該圖片的oss地址
                            'relative_path' => $ossFileName     //資料庫儲存名稱(相對路徑)
                        ];
                    } catch (OssException $e) {
                        return render(RENDER_CODE_FAIL, $e->getCode() . $e->getMessage());
                    }finally {
                        unlink($filePath);
                    }
                    return render(RENDER_CODE_SUCCESS, '成功',['path' => $arr['oss_url']]);
                }
                return render(RENDER_CODE_FAIL, $result['msg']);
            }
            
        }else{
            if($_FILES){
                $fileAll = $_FILES;
                foreach($fileAll as $file){
                    if($file['error']===0){
                        $name = $file['name'];
                        $format = strrchr($name, '.');//擷取檔案字尾名如 (.jpg)
                        /*判斷圖片格式*/
                        $allow_type = ['.jpg', '.jpeg', '.gif', '.bmp', '.png'];
                        if (!in_array($format, $allow_type)) {
                            return render(RENDER_CODE_FAIL, '檔案格式不在允許範圍內哦');
                        }
                        // 嘗試執行
                        try {
                            $config = config('api.aliyun_oss');
                            //print_r($config);die;
                            //例項化物件 將配置傳入
                            $ossClient = new OssClient($config['key_id'], $config['key_secret'], $config['endpoint']);
                            //這裡是有sha1加密 生成檔名 之後連線上字尾
                            $fileName = $ossUploadPath.'/' . date("Ymd") . '/' . sha1(date('YmdHis', time()) . uniqid()) . $format;
                            //執行阿里雲上傳
                            $result = $ossClient->uploadFile($config['bucket'], $fileName, $file['tmp_name']);
                            /*組合返回資料*/
                            $arr = [
                                'oss_url' => $result['info']['url'],  //上傳資源地址
                                'relative_path' => $fileName     //資料庫儲存名稱(相對路徑)
                            ];
                        } catch (OssException $e) {
                            return $e->getMessage();
                        }
                        //將結果返回
                        return render(RENDER_CODE_SUCCESS, '成功上傳到oss', ['file_url' => $arr['oss_url']]);
                    }
                    return render(RENDER_CODE_FAIL, '檔案不存在');
                }
            }
        }
        
    }

 base64_upload方法將資料轉換成二進位制並存儲到指定伺服器路徑 在上傳到oss

 /**
     * 將Base64資料轉換成二進位制並存儲到指定路徑
     * @param        $base64
     * @param string $path
     *
     * @return array
     */
    private function base64_upload($base64, $local_path = './upload/temp/') {
        $data = explode(',',$base64);
        trace($data,'api');
        unset($base64);
        if (count($data) !== 2){
            return render(RENDER_CODE_FAIL,'檔案格式錯誤');
        }
        if (preg_match('/^(data:\s*image\/(\w+);base64)/', $data[0], $result)){
             /*判斷圖片格式*/
            $allow_type = ['.jpg', '.jpeg', '.gif', '.bmp', '.png'];
            if (!in_array($result[2], $allow_type)) {
                return render(RENDER_CODE_FAIL, '檔案格式不在允許範圍內哦');
            }
            $image_name = md5(uniqid()).'.'.$result[2];
            $image_path = $local_path;
            $image_file = $image_path . $image_name;
            if(!file_exists($image_path)){
                mkdir($image_path, 0777, true); 
            }
            //伺服器檔案儲存路徑
            try {
                if (file_put_contents($image_file, base64_decode($data[1]))) {
                    return render(RENDER_CODE_SUCCESS, '成功', ['name' => $image_name, 'path' => $image_path]);
                } else {
                    return render(RENDER_CODE_FAIL, '檔案儲存失敗');
                }
            }catch (\Exception $e){
                return render(RENDER_CODE_FAIL,$e->getMessage());
            }
        }
        return render(RENDER_CODE_FAIL,'檔案格式錯誤');
    }