Ajax提交用FormData()上传文件
1.form声明如下
2.ajax设置如下
var formData = new FormData(document.getElementById("form"));
$.ajax({
url:document.form.action,
type:"POST",
data:formData,
processData:false, // 告诉jquery不要处理发送的数据
contentType:false, // 告诉jquery不要设置content-Type请求头
success:function(data){
if(data == "ok"){
window.parent.splitpageform.submit();
}
},
error:function(data){
}
});
3.后台controller接收方法
//将所有的照片都变成附件,这个是领用人上传照片节点要用到的,空的也加入list
public static List<Attachment> getMultipartFilesContainEmpty(HttpServletRequest request){
List<Attachment> attachs = new ArrayList<Attachment>();
try{
//创建一个通用的多部分解析器
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
//判断 request 是否有文件上传,即多部分请求
if(multipartResolver.isMultipart(request)){
//转换成多部分request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
//取得request中的所有文件名
Iterator<String> iter = multiRequest.getFileNames();
while(iter.hasNext()){
//取得上传文件
String key = iter.next();
List<MultipartFile> files = multiRequest.getFiles(key);
if(files != null && files.size() > 0 ){
for(MultipartFile file : files){
Attachment attach = FileLoad.upLoad(request, file);
if(null != attach){
attach.setTablename(key);
}else{
attach = new Attachment();
attach.setTablename("empty");
}
attachs.add(attach);
}
}
}
return attachs;
}
return attachs;
}catch(Exception e){
e.printStackTrace();
return attachs;
}
}