SSM+Ajax 实现上传实例(包含文件和其他属性)

**********************************
提交文件类的
@RequestMapping (value = "/uploadFileAjax" )
@ResponseBody
public Model uploadFiles( @ModelAttribute ( "CFlie" ) CFile cFile, Model model) {
try {
System. out .println( "====" +cFile.getFileName());
for ( int i = 0 ;i length ;i++){
String filePath = request .getSession().getServletContext().getRealPath( "/" ) + "/upload/" + cFile.getFile()[i].getOriginalFilename();
cFile.getFile()[i].transferTo( new File(filePath));
}

} catch (Exception e) {

}
return model;
}


**********************************
提交对象
public class CFile {
private String fileName ;
private MultipartFile[] file ;

public String getFileName() {
return fileName ;
}

public void setFileName(String fileName) {
this . fileName = fileName;
}

public MultipartFile[] getFile() {
return file ;
}

public void setFile(MultipartFile[] file) {
this . file = file;
}
}
***********************************
表单(引用bootstrap)
< form action= "/uploadFileAjax" method= "post" enctype= "multipart/form-data" id= "uploadFileForm" modelAttribute= "CFile" >
< div class= "box-body" >
< div class= "row " >
< div id= "message" class= "success" > ${ message } div >
< h5 class= "box-info col-xs-2" style= " width : 8 % " > 文档: h5 >

< input type= "text" name= "fileName" style= " width : 20 % " class= "form-control col-xs-2" />
< input type= "file" name= "file" style= " width : 20 % " class= "form-control col-xs-2" />
< input type= "file" name= "file" style= " width : 20 % " class= "form-control col-xs-2" />
< input type= "button" οnclick= " uploadFile () " class= "btn-primary"
style= " margin-top : 10 px ; margin-left : 20 px " value= "上传文件" >
div >
div >
form >
*************************************
ajax
function uploadFile () {
alert ( "ajax upload file" )
var formData = new FormData ( $ ( "#uploadFileForm" )[ 0 ]);
$ . ajax ({
type : "POST" ,
url : "/uploadFileAjax" ,
data : formData ,
async : false ,
cache : false ,
contentType : false ,
processData : false ,
success : function (data) {

}
}
);

}

你可能感兴趣的:(JavaWeb)