1、application.properties文件配置如下
server.port=8899
# 配置静态资源服务器的资源路径
# 默认情况下,我们的访问服务器时,端口号之后的路径是在访问当前项目static目录下的内容
# 例如localhost:8899/index.html 是在static目录下寻找index.html来显示
# 但是我们现在要访问的是F:/upload路径下的各种图片资源
# 所以我们要将默认的路径修改为F:/upload
# 这样我们再访问localhost:8899/a.jpg时,访问的就是F:/upload/a.jpg了
spring.resources.static-locations=file:F:/upload
# 上传文件的路径以及静态资源服务器的路径
knows.resource.path=file:F:/upload
knows.resource.host=http://localhost:8899
2、在Controller中编写如下代码
@Value("${knows.resource.path}")
private File resourcePath;
@Value("${knows.resource.host}")
private String resourceHost;
@PostMapping("/upload/file")
public String upload(MultipartFile imageFile) throws IOException {
String path= DateTimeFormatter.ofPattern("yyyy/MM/dd")
.format(LocalDateTime.now());
File folder=new File(resourcePath,path);
folder.mkdirs();
String filename=imageFile.getOriginalFilename();
String ext=filename.substring(filename.lastIndexOf("."));
String name= UUID.randomUUID().toString()+ext;
File file=new File(folder,name);
log.debug("文件上传路径:{}",file.getAbsolutePath());
imageFile.transferTo(file);
String url=resourceHost+"/"+path+"/"+name;
log.debug("回显上传图片的url:{}",url);
return url;
}