最近在做一个文件上传的功能,走了不少弯路,话不多说,直接上代码:
导入各种jar包,首先是applicationContext.xml配置文件中:
1 <!-- 配置文件解析器 --> 2 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 3 </bean>
写两个前端页面:upLoad.jsp
1 <body> 2 <form action="upload.do" method="post" enctype="multipart/form-data"> 3 姓名:<input type="text" name="username"/><br> 4 头像:<input type="file" name="mf"/><br> 5 姓名:<input type="submit" value="上传"/> 6 </form> 7 </body>
show.jsp
1 <body> 2 <h1>head image</h1> 3 <img alt="" src="${image }" style=" 400px;height: 500px"> 4 </body>
然后进入正题,写一个上传的战士页面的controller
@RequestMapping("/toUpload.do") //SpringMVC的映射标注 public String toUpload(){ return "upload"; }
然后
1 @Controller 2 public class FileUploadController { // MultipartFile 用于接受文件对象 3 @RequestMapping("/upload.do") // MultipartFile用于接受用户名和数据,否则文件上传时候也上encytype后悔接收不到数据 4 public String upload(String username, MultipartFile mf, HttpServletRequest req) { 5 6 System.out.println(username + "||" + mf.getOriginalFilename() + "||" + mf.getSize()); 7 // 把文件写入响应路径下 8 String realpath = req.getServletContext().getRealPath("images");// 获取到当前文件夹的真是路径 9 String orName = mf.getOriginalFilename();// 获取文件的原始名字 10 String fileName = System.currentTimeMillis() + orName.substring(orName.lastIndexOf("."));// 修改上传文件的名字,时间加后缀 11 String filePath = realpath + "/" + fileName; 12 System.out.println(filePath); 13 File file = new File(filePath);// 创建一个文件对象 14 try { 15 mf.transferTo(file);// 将文件写入到路径中 16 } catch (IllegalStateException e) { 17 e.printStackTrace(); 18 } catch (IOException e) { 19 e.printStackTrace(); 20 } 21 req.setAttribute("image", "images/" + fileName); 22 return "show"; 23 } 24 }
OK!,大功告成!