首先在配置文件中对文件保存路径进行设置
#指定文件上传的目录
photo:
files:
dir: D:\protect\thymeleaf\photos
然后在控制层对文件路径使用注解的方式进行注入
@Value("${photo.files.dir}")
private String realpath;
上传头像方法抽取
/*抽取方法:上传头像方法*/
private String uploadPhoto(MultipartFile img, String originalFilename) throws IOException {
String fileNamePrefix = new SimpleDateFormat("yyyyMMddhhmmssSSS").format(new Date());
String fileNameSuffix = originalFilename.substring(img.getOriginalFilename().lastIndexOf("."));
String newFileName = fileNamePrefix+fileNameSuffix;
img.transferTo(new File(realpath,newFileName));//transfreTo为图片传输方法
return newFileName;
}
另外在表单中类型要注意
enctype="multipart/form-data"
#application.yal文件中
spring:
web:
resources:
static-locations: classpath:/static/,file:${photo.files.dir} #暴露哪些资源可以被项目名访问