springMVC多文件上传并处理文件名

greensomnuss 2011-08-18

页面:

<html>
  <head>
  <script type="text/javascript" src="js/jquery-1.4.4.min.js"></script>
  <script type="text/javascript" src="js/jquery.form.js"></script>
  </head>
  <body>
  <form id="form" action="register.do" method="post" enctype="multipart/form-data">
   <label>请插入图片</label><input type="button" value="新增" id="add"><br>
   <table id="table">
   <tr><td>1</td><td><input name="file" type="file" /></td></tr>
   </table>
   <input type="button" id="btn" value="上传">
   </form>
  </body>
 <script type="text/javascript">
 $(function () {
 
 $("#btn").click(function () {
  $("#form").ajaxSubmit(
  function(data){
  if(data==1)alert("上传成功!");
  else alert("上传失败!");
  }
  ); 
});
var s=1;
$("#add").click(function(){
var size=document.getElementsByTagName("tr").length;
if(size<10){
s++;
var str="<tr><td>"+s+"</td><td><input name='file' type='file' /></td></tr>";
 $("#table").append(str);
}else{
alert("最多一次上传10个文件!");
}
})
 });
 </script>
  </html>

springMVC后台处理

@RequestMapping(value="register.do")
public void registerUser(HttpServletRequest req,HttpServletResponse res,ModelAndView model){
String path = req.getSession().getServletContext().getRealPath("/upload/"); // 获取本地存储路径
MultipartHttpServletRequest mul = (MultipartHttpServletRequest) req;
List<MultipartFile> files=mul.getFiles("file");
int msg=1;
try {
	for(int i=0;i<files.size();i++){
		CommonsMultipartFile mf=(CommonsMultipartFile) files.get(i);
		File file=new File(path + "/"+mf.getOriginalFilename());
		int index=mf.getOriginalFilename().lastIndexOf(".");
		String filename=mf.getOriginalFilename().substring(0, index);
		String extendname=mf.getOriginalFilename().substring(index);
		int ex=1;
		while(file.exists()){
			file=new File(path + "/"+filename+"("+ex+")"+extendname);
			ex++;
		}
		mf.getFileItem().write(file);
	}
} catch (Exception e) {
	msg=0;
	e.printStackTrace();
}
try {
	res.getWriter().print(msg);
} catch (IOException e) {
	e.printStackTrace();
}
}

  

相关推荐