js 提交表单数据: 附件+对象的的多集合

JavaScript010

js 提交表单数据: 附件+对象的的多集合,第1张

在我们前端进行表单提交的时候,有时候会出现这种情况:Failed to convert   java.lang.String    to java.util.List

等等。

例如:

  我后台定义一个对象:

       examPaper 包含  String userId,Float userScore, MultipartFile  examFile  用户id  ,试卷分数,试卷文件

对象外面   classPaper有: String classId  String className  List<examPaper>  examPaperList

这个时候,后台接收为  ClassPaper

如果按照平常的 form-data   提交  则应按以下方式提交:

let  fd  = new FormData()

fd.append("classId ",classId )

fd.append("className ",className )

examPaperList.forEach((item,index) ->{

     fd.append("examPaperList["+index+"].userId",item.userId)

     fd.append("examPaperList["+index+"].userScore",item.userScore)

     fd.append("examPaperList["+index+"].examFile ",item.examFile )

})

以这种方式就可以实现 多附件  一一 对应提交。以避免对象转换错误问题。

第一次写这种文章。

1.    原生js中,form表单在提交数据的时候默认的编码格式是application/x-www-form-urlencoded

2.    如果表单中有文件需要上传,那么必须在form元素中添加除了action和method(如果是get请求,可以不添加method属性。默认情况下,form表单以get方式提交表单数据)之外的第3个属性enctype,并且设置enctype="multipart/form-data"。

参考页面: HTML