问题:直接在action中写后端地址会出现跨域问题

解决:用http-request指定具体上传方法

el-upload代码如下,action中随便写,反正用不到

<el-upload
            class="avatar-uploader"
            action="string"
            :show-file-list="false"
            :http-request="uploadImage"
            :before-upload="beforeAvatarUpload">
            <img v-if="form.picUrl" :src="form.picUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
// 上传图片方法
    uploadImage(param){
      const formData = new FormData()
      formData.append('file', param.file)
      uploadAvatar(formData).then(response => {
        console.log('上传图片成功')
        this.form.picUrl = process.env.VUE_APP_BASE_API + response.imgUrl
      }).catch(response => {
        console.log('图片上传失败')
      })
    },

上述代码中uploadAvatar方法如下

// 文件上传
request({
    url: '/system/file/upload',
    method: 'post',
    data: data
  })

照片上传前校验代码如下

// 资质照片上传前校验
    beforeAvatarUpload(file) {
      const isPic = file.type.indexOf('image') >= 0;
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isPic) {
        this.$message.error('资质照片只能为图片格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return isPic && isLt2M;
    },

附加:上传方法为传递自定义参数 

:http-request="(param) => uploadImage(param,4)"

其中4为自定义参数

Logo

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐