1.导入需要的jar包(fileupload,commons-io)
2.网页表单提交格式post,编码要enctype="multipart/form-data",上传文件要有name
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>register</title> </head> <body> <form action="/SpringMVC/user/register" method="post" enctype="multipart/form-data"> name:<input type="text" name="name"/><br/> password:<input type="password" name="password"/><br/> phone:<input type="text" name="phone"/><br/> age:<input type="text" name="age"/><br/> photo:<input type="file" name="photo"/><br/> <input type="submit" value="提交"/><br/> </form> </body> </html> |
3.在Controller里处理
@RequestMapping("register") public ModelAndView register(User user,MultipartFile phot,HttpServletRequest request) { ModelAndView mv=new ModelAndView("register"); //1.通过request获取文件真实上传路径 String pathname=request.getServletContext().getRealPath("/photo"); //2.通过真实路径创建文件 File file=new File(pathname); if(!file.exists()) {//判断是否存在,若不存在则新建 file.mkdirs(); } //3.通过MultipartFile对象获取文件名 String fileName=phot.getOriginalFilename(); user.setPhoto(fileName); File targetFile=new File(pathname+"/"+fileName);
try { //4.通过FileUtils把MultipartFile的文件复制到目标文件 FileUtils.writeByteArrayToFile(targetFile, phot.getBytes()); } catch (IOException e) { e.printStackTrace(); } request.setAttribute("user", user); return mv; } |
4.在springMVC中配置文件上传解析器
<!-- 配置文件上传解析器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 设置最大文件字节 --> <property name="maxInMemorySize" value="200000"></property> </bean> |
注意:网页上传文件的name要和实体类中放文件路径的属性不一样否则会报错