js 模拟POST提交enctype="multipartform-data"类型的表单

JavaScript06

js 模拟POST提交enctype="multipartform-data"类型的表单,第1张

只是需要文件上传才用它的

xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded")

改成

xmlHttp.setRequestHeader("Content-Type","multipart/form-data")。

js模拟post提交的代码

通过js模拟post提交

1:请求需要的参数过长,超过get允许的最大长度

2:想要隐藏地址栏的参数

//新创建一个form表单

document.write('<form name=myForm></form>') 

var myForm=document.forms['myForm'] 

myForm.action='runEmpAttendance' 

myForm.method='POST'

var input = document.createElement('input')

input.type = 'text'

input.name = 'userId'

input.value = 100

myForm.appendChild(input)

myForm.submit()

//使用jsp中已经存在的form表单,添加其他的参数

var myForm = document.forms['listEmployee']  //表单的name

var input = document.createElement('input')

input.type = 'hidden'

input.name = 'currentPage'

input.value = 1

myForm.appendChild(input)

myForm.method= 'POST'

myForm.submit()。

在我们前端进行表单提交的时候,有时候会出现这种情况: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 )

})

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

可以手动构建一个FormData进行表单提交,代码如下:

var form = new FormData()

//添加参数

form.append('name', 'jack')

form.append('age', 20)

//使用xmlhttprequest发起请求

var xhr = new XMLHttpRequest()

xhr.open('post', '这里添上请求的url', true)

xhr.onreadystatechange = function() {

    if(xhr.readyState == 4) {

        //成功

    }

}

//执行请求

xhr.send(form)