关于multipart/form-data不能提交嵌套JSON对象

需求:axios上传文件,同时还要提交简单的键值对和复杂嵌套的数据

contentType为multipart/form-data


import axios from 'axios'
var instance2 = axios.create({
  headers: { 'Content-Type': 'multipart/form-data' }
})    

let formData = new FormData()
for (let key in this.inp) {
    formData.append(key, this.inp[key])
  }
  axios.instance2.post('/webswmm/data/inp', formData ).then(({ data }) => {        
    console.log(data)
  })

// inp
  inp: {
    authority: 'private',
    files: []
  },

FormData模拟提交包含简单键值对和文件的Form表单时,如果是post请求,数据会以键值对形式被放在请求体中,这两个部分是没有问题的,后端springboot这样接收就可以了

@RestController
@RequestMapping("/webswmm/data")
@Api("上传数据")
public class DataController {

    @PostMapping(value = "/inp")
    public ResponseResult uploadFile(@RequestParam("authority") String authority,   @RequestParam("files") MultipartFile[] files){
        return null;
    }
}

但是,笔者的需求是inp还想包含其他的嵌套信息

      inp: {
        authority: 'private',
        projection: {
          code: '',
          name: '',
          extend: [],
          unit: '',
          proj4def: ''
        },
        files: []
      },

这样提交以后,后端接收到的projection是object,无法解析出projection的值。原因是multipart/form-data本来就只能发送文件和不嵌套的键值对,所以发送这样的inp肯定是不行的。

解决办法:

      inp: {
        authority: 'private',
        projection: '',
        files: []
      },

把需要嵌套的json数据在发送前用JSON.stringfy()方法转为json字符串,放入form表单中,就可以了




import axios from 'axios'
var instance2 = axios.create({
  headers: { 'Content-Type': 'multipart/form-data' }
})    

var curProjction = {}
curProject.code = '3857'
curProjction.name = 'WGS:84'
// ...其他属性赋值
this.inp.projection = JSON.stringify(curProjction)

let formData = new FormData()
for (let key in this.inp) {
    formData.append(key, this.inp[key])
  }
  axios.instance2.post('/webswmm/data/inp', formData ).then(({ data }) => {        
    console.log(data)
  })

// inp
  inp: {
    authority: 'private',
    files: []
  },

后端:

@RestController
@RequestMapping("/webswmm/data")
@Api("上传数据")
public class DataController {

    @PostMapping(value = "/inp")
    public ResponseResult uploadFile(@RequestParam("authority") String authority,   @RequestParam("files") MultipartFile[] files,@RequestParam("projection") String projection){
// 解析projection
        return null;
    }
}

 

你可能感兴趣的:(axios)