1. SpingMVC实现上传功能也是相当的简单,但是要做如下几件事情
    1. <dependency>
    2. <groupId>commons-fileupload</groupId>
    3. <artifactId>commons-fileupload</artifactId>
    4. <version>1.3.1</version>
    5. </dependency>
    1. <!--必须通过文件解析器的解析才能将文件转换为MultipartFile对象-->
    2. <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>

    页面:

    1. <form th:action="@{/upload}" method="post" enctype="multipart/form-data">
    2. 头像:<input type="file" name="photo"><br>
    3. <input type="submit" value="上传">
    4. </form>

    代码

    1. @PostMapping("upload")
    2. public String upload(MultipartFile photo,HttpSession httpSession) throws IOException {
    3. ServletContext servletContext = httpSession.getServletContext();
    4. String realPath = servletContext.getRealPath("upload.jpg");
    5. Files.copy(photo.getInputStream(),Paths.get(realPath));
    6. return "success";
    7. }
    1. 需要注意,在IDEA中上传的位置在:

    image.png