文件上传
文件上传Maven依赖文件上传jar包
<dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-io/commons-io --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency>
表单增加user上传头像,form表单需要增加enctype="multipart/form-data",其中“/file”为idea的虚拟文件映射
<tr> <td>个人头像</td> <td> <c:if test="${user.portal !=null }"> <img src="/file/${user.portal}" width="100" height="100"/> </c:if> <input type="file" name="user_portal"/> </td> </tr>
多部件文件解析
<!--多部件类型解析--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="5242880"/> //最大5M <property name="defaultEncoding" value="utf-8"/> </bean>
Controller处理
@RequestMapping(value="/showUser",method= RequestMethod.POST) public ModelAndView showUser(@Valid User user, BindingResult bindingResult, MultipartFile user_portal) throws IOException {
//user_portal要和前台的name保持一致 String filename = user_portal.getOriginalFilename(); if(user_portal!=null && filename!=null && filename.length()>0){ String path="D:\\spring_project\\chapter17\\pic_repo\\"; String newName=UUID.randomUUID()+filename.substring(filename.lastIndexOf(".")); File newFile = new File(path + newName); if(!newFile.exists()) newFile.mkdirs(); user_portal.transferTo(newFile); user.setPortal(newName); }
参考:
https://blog.csdn.net/eson_15/article/details/51742864
立志如山 静心求实