php 前端/后端 base64传输

后台代码解析

 public function actionImg(){
        $post = \Yii::$app->request->post();
        if(!$post){
            return json_encode(array('status'=>0,'msg'=>'数据为空'));
        }
        if(!$post['file']){
            return json_encode(array('status'=>0,'msg'=>'参数错误'));
        }
        $file = preg_split("/(,|;)/",$post['file']);
        $base64Data = $file[2];                                              //文件信息
        $arr2 = explode('/',$file[0]);                                     //分割出图片格式
        $type = $arr2[1];                                                      //文件类型
        $str = time().rand(10000,99999);                                     //生成图片名
        $basePath = \Yii::$app->basePath;                                    //yii 获取项目根目录
        $fileName = $basePath.'\upload\img\\'.$str.'.'.$type;                //拼接图片名称
        $return = file_put_contents($fileName,base64_decode($base64Data));   //存储图片到服务器
        if($return){
            $imgsuffix = strtolower(strstr($str, '.'));
            $imgname = 'photo/homework/'.time().rand(1000,9999).$imgsuffix.'.'.$type;
            //oss配置
            $bucket = \Yii::$app->params['oss']['bucket'];
            $accessKeyId = \Yii::$app->params['oss']['accessKeyId'];
            $accessKeySecret = \Yii::$app->params['oss']['accessKeySecret'];
            $endpoint = \Yii::$app->params['oss']['endpoint'];
            //上传至OSS
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            try {
                //图片上传
                $ossClient->uploadFile($bucket, $imgname, $fileName);
            } catch (OssException $e) {
                return \GuzzleHttp\json_encode(array('status'=>0,'msg'=>$e));
            }
            return \GuzzleHttp\json_encode(array('status'=>1,'msg'=>'图片上传成功','data'=>array('imgurl'=>$imgname)));
        }else{
            return json_encode(array('status'=>0,'msg'=>'文件流解析错误'));
        }
    }

前端ajax 提交


                  点击上传
                  只能上传jpg/png文件,且不超过2MB


imgBeforeUpload(file){
        const self = this
        var File;
        let reader = new FileReader()
        reader.readAsDataURL(file) //转BASE64
        reader.onload=function(e) {
          File = e.target.result
          
          AXIOS.post('/courseware/courseware/img', {
            file: File
          })
          .then(res => {
            console.log(res)
          })
        }
        return false
}

你可能感兴趣的:(ajax)