vue + elementui + axios表单数据和文件上传,springboot接收

https://blog.csdn.net/gaopinqiang/article/details/107328936

前端JS代码:

apply(){

        let data = new FormData();

        // todo 非常重要,一定要加file.raw,从浏览器中查看需要使用binary类型,后台才能正确接收
        this.form.files = this.fileList[0].raw
        console.log(this.fileList[0].raw)
        

        // 将form表单中的值都赋值给FormData传递给后台
        for(let key in this.form){
          console.log(this.form[key])
          data.append(key,this.form[key])
        }

        this.$axios
          .post('/user/apply',data,{
            headers: {
              'Content-Type': 'multipart/form-data'
            }})// 第一种,直就传个json数据,不需要设置headers

          // .post('/user/apply',this.form)// 第三种,可以直接传递这个form(推荐)

          .then(resp => {
            console.log('请求本地接口OK')
            console.log(resp)

            if(resp.data.code == -1){
              // 接口返回-1,就是注册失败,提示消息提示用户
              this.$message({
                message: resp.data.msg,
                type: 'error'
              });
            } else if(resp.data.code == 0){
              console.log(resp.data)
              //注册成功
              this.$message({
                message: "报名成功",
                type: 'success'
              });

              // 跳转到登录页面
              // this.$router.push('/login')

            }

          })
          .catch(function (error) { // 请求失败处理
            console.log('请求本地接口失败' + error);
          });
      },

Java代码:

@Transactional
    @ApiOperation(notes = "报名参加接口", value = "报名参加接口", httpMethod = "POST")
    @PostMapping(value = "/apply",produces = "application/json;charset=UTF-8")
    public Result apply(RegistrationInfo registrationInfo, @RequestParam(value = "files")MultipartFile files){
        //同时接收RegistrationInfo这个bean参数和参数名为files的MultipartFile类型参数。
        //我们使用DataForm,格式提交就可以。
        ...
        
    }

 

posted @ 2021-05-25 18:05  野生野鸡码农  阅读(929)  评论(0编辑  收藏  举报