文件上传要求form表单的请求方式必须为post,并且添加属性enctype="multipart/form-data" SpringMVC中将上传的文件封装到MultipartFile对象中,通过此对象可以获取文件相关信息。

    上传步骤:
    1、添加依赖:

    1. <!--https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload-->
    2. <dependency>
    3. <groupId>commons-fileupload</groupId>
    4. <artifactId>commons-fileupload</artifactId>
    5. <version>1.3.1</version>
    6. </dependency>

    2、在SpringMVC的配置文件中添加配置:

    1. <!--必须通过文件解析器的解析才能将文件转换为MultipartFile对象-->
    2. <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> </bean>

    3、控制器方法:

    1. @RequestMapping("/testUp")
    2. public String testUp(MultipartFile photo, HttpSession session) throws IOException {
    3. //获取上传的文件的文件名
    4. String fileName = photo.getOriginalFilename();
    5. //处理文件重名问题
    6. String hzName = fileName.substring(fileName.lastIndexOf("."));
    7. fileName = UUID.randomUUID().toString() + hzName;
    8. //获取服务器中photo目录的路径
    9. ServletContext servletContext = session.getServletContext();
    10. String photoPath = servletContext.getRealPath("photo");
    11. File file = new File(photoPath);
    12. if(!file.exists()){
    13. file.mkdir();
    14. }
    15. String finalPath = photoPath + File.separator + fileName;
    16. //实现上传功能
    17. photo.transferTo(new File(finalPath));
    18. return "success";
    19. }