vue+springboot同时接收上传的文件和json(代码)

前端:templete中

<input type="file" value="" id="file" @change="uploadTest">

script中

methods: {
    uploadTest (e) {
      let formData = new FormData()
      let data = JSON.stringify({
        aa: 'xxx',
        bb: 123
      })
      formData.append('file', e.target.files[0])
      formData.append('data', new Blob([data], {type: 'application/json'})) // 同时上传文件和JSON,这里1.用动new Blob;2[data]中括号;3.必须加type,postman见本站https://blog.csdn.net/FRESHET/article/details/121286971

      //   后台测试地址
      let url = 'http://192.168.1.103:8081/upload'
      let config = {
        headers: {'Content-Type': 'multipart/form-data'}
      }
      this.$axios.post(url, formData, config).then(function (response) {
        console.log(response.data)
      })
    }
  }

后台代码:

@CrossOrigin
    @PostMapping("/upload")
    @ResponseBody
    public String upload(@RequestPart("file") MultipartFile file,@RequestPart Map<String,Object> data ) {
        if (file.isEmpty()) {
            return "上传失败,请选择文件";
        }

        String fileName = file.getOriginalFilename();
        String filePath = "E:\\vuetest\\vue_upload\\";
        File dest = new File(filePath + fileName);
        try {
            file.transferTo(dest);
            System.out.println(data.get("aa"));
            System.out.println(data.get("bb"));
            System.out.println("upload ok");
            return "上传成功";
        } catch (IOException e) {
            System.err.println(e.toString());
        }
        return "上传失败!";
    }

效果:

xxx
123
upload ok 

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值