1. 在pom.xml中导入依赖
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
2.JSP页面头部添加代码防止乱码
<meta http-equiv="Content-Type" content="multipart/formdata;charset=utf-8" />
enctype="multipart/form-data"
4.编写Controller层代码
@RequestMapping("/test")
public String shengadd(HttpServletRequest request, Obj obj, MultipartFile pictureFile) throws Exception {
System.out.println("***");
//使用UUID给图片重命名,并去掉四个“-”
String name = UUID.randomUUID().toString().replaceAll("-", "");
//获取文件扩展名
String ext = FilenameUtils.getExtension(pictureFile.getOriginalFilename());
//设置图片上传路径
String url = request.getSession().getServletContext().getRealPath("/static/img");
//以绝对路径保存重命名后的图片
pictureFile.transferTo(new File(url + "/" + name + "." + ext));
//把图片储存路径保存到数据库
obj.setImg("statics/img/" + name + "." + ext);
xxxService.save(obj);
return "redirect:/test.html";
}
5.在sprinngmvc.xml添加文件上传解析器
<!-- 定义文件上传解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设定默认编码 -->
<property name="defaultEncoding" value="UTF-8"></property>
<!-- 设定文件上传的最大值5MB,5*1024*1024 -->
<property name="maxUploadSize" value="5242880"></property>
</bean>
支持原创作者,点击跳转至参考文章