# 在配置文件中指定文件上传位置
photo:
file:
dir: E:\IdeaProjects\maven\springboot\ems-thymeleaf2\photo
//编写接口
@Value("${photo.file.dir}")
private String realPath;
@PostMapping("/save")
public String save(Employee employee, MultipartFile img) throws IOException {
// MultipartFile是spring类型,代表HTML中form data方式上传的文件,包含二进制数据+文件名称
String originalFilename = img.getOriginalFilename();
//1.处理头像的上传&修改文件名称
//1.1时间戳作为文件名前缀
String fileNamePrefix = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
//1.2截取文件名后缀
String fileNameSuffix = originalFilename.substring(originalFilename.lastIndexOf('.'));
//1.3拼接成新的文件名
String newFileName = fileNamePrefix + fileNameSuffix;
img.transferTo(new File(realPath,newFileName));
//2.保存员工信息
employee.setPhoto(newFileName);//保存头像名
employeeService.save(employee);
return "redirect:/employee/lists";
}
- 文件上传:1.表单提交方式必须是post 2.表单enctype属性必须为 multipart/form-data
<form th:action="@{/employee/save}" method="post" enctype="multipart/form-data">
#开启资源暴露,设置后可以直接通过路径访问到图片
spring:
#暴露哪些资源可以通过项目名访问,自己写的会覆盖原有的,所以需要把static写上
web:
resources:
static-locations: classpath:/static/,file:${photo.file.dir}
#可以修改日期格式(springboot默认是xxx/xxx/xxx),没有按指定格式输入则会报错
spring:
mvc:
date-format: yyyy-MM-dd
- 需要拼接上@{/}才可以当作链接去访问
头像
<img th:src="@{/}+${employee.photo}" width="60">
版权声明:本文为m0_53249319原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。