antd vue pro中使用customRequest,以FormData方式进行自定义上传图片,java后台接收

1、vue部分

<a-upload
          :multiple="false"
          name="avatar"
          list-type="picture-card"
          class="avatar-uploader"
          :show-upload-list="false"
          :before-upload="beforeUpload"
          :customRequest="customRequest"
        >
          <img v-if="imageUrl" :src="imageUrl" alt="avatar" />
          <div v-else>
            <a-icon :type="loading ? 'loading' : 'plus'" />
            <div class="ant-upload-text">
              选择图片
            </div>
          </div>
        </a-upload>
//上传前验证
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        this.$message.error('请上传图片文件');
      }
      const isLt2M = file.size / 1024 / 1024 < 20;
      if (!isLt2M) {
        this.$message.error('文件不得超过20M!');
      }
      return isJpgOrPng && isLt2M;
    },
    
 // 自定义上传
    customRequest(file){
      const form = new FormData()
      form.append('file', file.file)
      // 用自己的接口
      console.log(form);
      uploadImg(form).then(res => {
        console.log(res);
        if (res.success) {
          // 调用组件内方法, 设置为成功状态
          file.onSuccess(res, file.file)
          file.status = 'done'
          this.imageUrl = res.message;
        } else {
          file.onError()
          file.status = 'error'
        }
      })
    },

api.js 里添加上传文件的请求

//上传文件
export function uploadImg (formdata) {
  return request({
    url: api.uploadImg,//后台访问的路径
    method: 'post',
    data: formdata,
    headers: { 'Content-Type': 'multipart/form-data' },//'Content-Type': 'multipart/form-data'
  })
}

2、java后台:使用的jeecgboot框架的自带上传方法,懒得改直接贴上来了

 @RequestMapping(value = "uploadImg", method = RequestMethod.POST)
    public Result<?> upload(HttpServletRequest request,HttpServletRequest response) throws Exception {
        Result<?> result = new Result<>();
        String savePath = "";
        String bizPath = request.getParameter("biz");
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("file");// 获取上传文件对象
        savePath =  this.uploadLocal(file,bizPath);  //调用上传方法返回保存的路径
        if(oConvertUtils.isNotEmpty(savePath)){
            result.setMessage(savePath);
            result.setSuccess(true);
        }else {
            result.setMessage("上传失败!");
            result.setSuccess(false);
        }
        return result;
    }
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值