php/PHP 阿里云OSS文件上传

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35979073/article/details/82866598

 一、封装的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,'文件格式错误');
    }

猜你喜欢

转载自blog.csdn.net/qq_35979073/article/details/82866598