springMVC多文件上传并处理文件名
页面:
<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(); } }
相关推荐
dlutbob 2020-06-17
MicroBoy 2020-06-05
横云断岭 2020-03-08
haidaoxianzi 2020-03-04
也许不会看见 2020-02-21
whbing 2020-02-14
Richardxx 2020-01-04
Richardxx 2019-12-24
whbing 2019-12-14
方志朋 2019-12-08
凯哥Java 2019-11-03
zlllxl00 2017-08-20
凯哥Java 2019-10-26
cloudspring 2014-08-14
RogerCoderLife 2019-07-01
MayMatrix 2018-08-06
Sweetdream 2017-08-20
白净垃圾桶 2014-08-22