SpingMVC实现上传功能也是相当的简单,但是要做如下几件事情
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<!--必须通过文件解析器的解析才能将文件转换为MultipartFile对象-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
页面:
<form th:action="@{/upload}" method="post" enctype="multipart/form-data">
头像:<input type="file" name="photo"><br>
<input type="submit" value="上传">
</form>
代码
@PostMapping("upload")
public String upload(MultipartFile photo,HttpSession httpSession) throws IOException {
ServletContext servletContext = httpSession.getServletContext();
String realPath = servletContext.getRealPath("upload.jpg");
Files.copy(photo.getInputStream(),Paths.get(realPath));
return "success";
}
需要注意,在IDEA中上传的位置在: