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

向后台接口传递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 ~

  • 8
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值