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

    上传步骤:
    ①添加依赖:

    1. <!--文件上传需要的依赖-->
    2. <dependency>
    3. <groupId>commons-fileupload</groupId>
    4. <artifactId>commons-fileupload</artifactId>
    5. <version>1.3.1</version>
    6. </dependency>

    ② 在SpringMVC的配置文件中添加配置:

    1. <!--配置文件上传解析器,将上传的文件封装为MultipartFile-->
    2. <bean id="multipartResolver"
    3. class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    4. </bean>
    1. ③控制器方法:(语法基本固定)
    1. //文件上传
    2. @RequestMapping("/testUp")
    3. public String testUp(MultipartFile photo,HttpSession session) throws IOException {
    4. String fileName = photo.getOriginalFilename();//获取上传文件的文件名
    5. //获取上传的文件的文件名
    6. String suffixName = fileName.substring(fileName.lastIndexOf("."));
    7. //将UUID作为文件名
    8. String uuid = UUID.randomUUID().toString();
    9. //将uuid和后缀名拼接后的结果作为最终的文件名
    10. fileName = uuid + suffixName;
    11. //通过ServletContext获取服务器中photo目录的路径
    12. ServletContext servletContext = session.getServletContext();
    13. String photoPath = servletContext.getRealPath("photo");
    14. File file = new File(photoPath);
    15. //判断photoPath所对应的路径是否存在
    16. if (!file.exists()){
    17. //若不存在,则创建目录
    18. file.mkdir();
    19. }
    20. String finalPath = photoPath + File.separator + fileName;
    21. photo.transferTo(new File(finalPath));
    22. return "success";
    23. }

    效果:(文件名为uuid)
    image.png