element-admin 上传 跨域 问题 http-request

感谢

https://www.jianshu.com/p/55c0bd5b5b3e

解决跨域问题的方法之一,使用上传组件的自定义上传方法 http-request

 

一般我们在用element-ui上传功能时,有个action属性填写上传图片地址,然后就能运用提供的各种钩子函数处理成功,失败等情况,但有时上传图片发请求时可能要做些特殊处理,比如跨域、特殊参数等,这是就要用到http-request这个方法了
1.首先要用任意字符覆盖action属性
 <el-upload
      class="image-upload-pic"
      ref="upload"
      action="fakeaction"
      :show-file-list="false"
      :http-request="uploadSectionFile"
    >
        <img v-if="imageUrl" :src="imageUrl" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>

2.用自己方法覆盖默认上传行为

3.根据请求返回的code就能处理各种情况,不需要利用默认钩子函数

methods:{
    uploadSectionFile(params) {
          const file = params.file,
            fileType = file.type,
            isImage = fileType.indexOf("image") != -1,
            isLt2M = file.size / 1024 / 1024 < 2;
          // 这里常规检验,看项目需求而定
          if (!isImage) {
            this.$message.error("只能上传图片格式png、jpg、gif!");
            return;
          }
          if (!isLt2M) {
            this.$message.error("只能上传图片大小小于2M");
            return;
          }
          // 根据后台需求数据格式
          const form = new FormData();
          // 文件对象
          form.append("file", file);
          // 本例子主要要在请求时添加特定属性,所以要用自己方法覆盖默认的action
          form.append("clientType", 'xxx');
          // 项目封装的请求方法,下面做简单介绍
          imageUpload(form)
            .then(res => {
             //自行处理各种情况
              const code = res && parseInt(res.code, 10);
              if (code === 200) {
                // xxx
              } else {
                // xxx
              }
            })
            .catch(() => {
              // xxx
            });
    } 
}

 利用axios简单封装的请求

const imageUpload = param => {
    const url = 'xxxxx'
    // 根据后台需求的数据格式确定headers
    return axios.post(url, params, { 
        headers: {"content-type": "multipart/form-data"}
    })
}

分析覆盖方法http-request传入的默认参数

{
    action:"fakeaction"
    data:undefined
    file:File(879394) {uid: 1558602694174, name: "Chrysanthemum.jpg", lastModified: 1247549551674, lastModifiedDate: Tue Jul 14 2009 13:32:31 GMT+0800 (中国标准时间), webkitRelativePath: "", …}
    filename:"file"
    headers:{__ob__: Observer}
    onError:ƒ onError(err)
    onProgress:ƒ onProgress(e)
    onSuccess:ƒ onSuccess(res)
    withCredentials:false
}

发现有触发默认钩子函数onError,onProgress,onSuccess的方法,所以你也根据自己图片上传请求的结果自己调用这些钩子方法,从而复用默认的ui

posted @ 2021-10-20 11:48  西瓜霜  阅读(653)  评论(0编辑  收藏  举报