1.JSP中注意两个属性和pageEncoding编码类型
enctype="multipart/form-data"
method="post"
2.控制器中
将自动绑定文件到file
@RequestParam("file") MultipartFile file
3.xml中配置
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 上传文件大小上限-->
<property name="maxUploadSize" value="10485760"/>
<!-- 请求的编码格式,必须和jsp的pageEncoding属性一致,以便正确的读取表单内容.默认iso-8859-1-->
<property name="defaultEncoding" value="UTF-8"/>
</bean>
4.需要添加的jar
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
接收示例:
System.out.println(description);
//如果文件不为空,写入上传路径
if (!file.isEmpty()) {
//上传文件路径
String path = request.getServletContext().getRealPath("/images/");
//上传文件名
String fileName = file.getOriginalFilename();
File filePath = new File(path, fileName);
//判断路径是否存在,如果不存在创建一个
if (!filePath.getParentFile().exists()) {
filePath.getParentFile().mkdirs();
}
//将上传文件保存到一个目标文件当中//把内存中的图片写入硬盘,transferTo是SpringMvc封装的一个方法
file.transferTo(new File(path + File.separator + fileName));
return "success";
} else {
return "error";
}