1.添加依赖
<!--文件上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.1</version>
</dependency>
2.在springMVC.xml配置文件中添加文件上传解析器
<!--文件上传解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10485760"></property>
<property name="defaultEncoding" value="utf-8"></property>
</bean>
3.文件上传页面uploadpage.jsp的部分代码,前端用了bootstrap
<form action="saveImg?username=${username}" method="post" enctype="multipart/form-data">
<h4><span>请选择头像:</span>
<input type="file" name="pic" id="pic"/>
</h4>
<input type="submit" class="btn btn-primary" value="上传"/>
</form>
4.FileController文件
@RequestMapping("/saveImg")
public String saveImg(@RequestParam("pic")MultipartFile file, HttpServletRequest request, Model model) throws Exception {
// 图片的路径,图片上传成功后,将路径保存到数据库
String filePath = request.getSession().getServletContext().getRealPath("img");
// 生成文件新的名字
String newFileName = UUID.randomUUID() + ".jpg";
// 封装上传文件位置的全路径
File targetFile = new File(filePath, newFileName);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
file.transferTo(targetFile);
//获得此用户名
String username = request.getParameter("username");
//将文件路径存进数据库
userService.upload(username,newFileName);
model.addAttribute("newFileName",newFileName);
return "/user_info";
}
5.图片显示页面user_info.jsp部分代码,用了bootstrap
<h4><span>头像:</span>
<img alt="" src="img/${newFileName}" height="150" width="150" id="images"
onerror="this.src='img/default.jpg'" class="img-rounded">
</h4>
οnerrοr="this.src=‘img/default.jpg’"表示的是当没有图片时显示默认图片default.jpg