我们在使用ajax提交表单时,如果想同时上传表单文件,正常提交时后台接受File值为空,如需提交时携带文件,可使用FormData,代码如下:
JSP:
<form id=
"index_form"
name=
"index_form"
role=
"form"
method=
"post"
class
=
"form-horizontal"
enctype=
"multipart/form-data"
>
<table>
<tr> <td> 图片一 : <input id=
"pic1"
name=
"pic1"
type=
"file"
onchange=
"pic1()"
/> </td> </tr>
<tr> <td> 用户名 : <input id=
"pic2"
name=
"pic2"
type="text"
/> </td> </tr>
<tr> <td> 密码: <input id=
"pic3"
name=
"pic3"
type=
"text"
/></td> </tr>
</table>
<input
value=
"提交"
type=
"submit"
/>
</form>
JS:
var file = $("#fileId").get(0).files[0];
var formData = new FormData();
formData.append("file",file);
$.ajax({
url:uploadFileUrl,
type:"POST",
async : false,
dataType:"json",
data:formData,
contentType: false,
processData: false,
success:function(data) {
}
});
var artform = $("#expert_form").serialize()";
$.ajax({
cache : true,
type : "post",
url : submitFormUrl,
data : artform,
async : false,
success : function(data) {
},
error : function(request) {
}
});
action:
需要两个action,一个为上传文件的action,一个为提交表单的action。
注意:如果用两个ajax(一个上传文件,一个提交表单),需设置 async : false,
ajax方法默认是异步执行的,即不管有没返回结果都可以继续往下执行
要想等ajax方法返回结果再执行下面的方法,需要设置为同步async:false