向后台接口传递FormData格式的数组对象

在js中,new FormData() 对象后,可以通过 append(name, value) 的方式往该对象中添加添加数据。然而append的值只能是字符串或者blob(File)格式,对于复杂的数组中包含对象的数据怎么添加呢?下面是我使用的方法:

后台接口要求的入参格式:

<input type="text" name="title"/>
<input type="file" name="file"/>
<input type="text" name="description"/><br/>
<input type="text" name="chapterList[0].title"/>
<input type="file" name="chapterList[0].file"/>
<input type="text" name="chapterList[0].description"/><br/>
<input type="text" name="chapterList[1].title"/>
<input type="file" name="chapterList[1].file"/>
<input type="text" name="chapterList[1].description"/>

此种数据相当于json格式的:

{
  "title": "title",
  "file": file,
  "description": "description",
  "chapterList": [
	{
	  "title": "title0",
	  "file": file0,
	  "description": "description0"
	},
	{
	  "title": "title1",
	  "file": file1,
	  "description": "description1"
	}
  ]
}

使用FormData处理如下:

// vue data中的数据
form: {
    description: '',
    file: null,
    title: '',
    // 动态添加部分数据
    chapterList: [
      {
        title: '',
        file: null,
        description: ''
      }
    ]
  }
// 转Formdata格式数据处理
 let data = new FormData()
 data.append('description', this.form.description)
 data.append('file', this.form.file)
 data.append('title', this.form.description)
 this.form.chapterList.forEach((item, i)=> {
   data.append(`chapterList[${i}].title`, item.title)
   data.append(`chapterList[${i}].file`, item.file)
   data.append(`chapterList[${i}].description`, item.description)
})

最后将data放在接口的参数里传给后台就可以啦~

the end ~

Logo

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

更多推荐