1.引入依赖
<!-- io常用工具类 -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
2.yml配置
web:
upload-path: D:\graduation-design-images\ # 图片保存位置
spring:
web:
resources:
static-locations:classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:${web.upload-path}
3.静态资源处理配置
public class WebConfig implements WebMvcConfigurer {
@Value("${web.upload-path}")
private String fileSavePath;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry){
// addResourceHandler("/graduation-design-images/**")表示凡事以 /graduation-design-images/ 路径发起请求的,按照 addResourceLocations("file:"+fileSavePath)的路径进行映射
registry.addResourceHandler("/graduation-design-images/**").addResourceLocations("file:"+fileSavePath);
}
}
4.controller层
@Value("${web.upload-path}")
private String uploadPath;
@PostMapping("/upload")
public String upload(@RequestParam MultipartFile uploadFile) throws IOException {
if(uploadFile.isEmpty()) return "参数为空";
// 获取文件名
String originName = uploadFile.getOriginalFilename();
// 获取文件后缀
String suffix = originName.substring(originName.lastIndexOf('.')+1);
// 使用uuid作为新的文件名
String fileName = UUID.randomUUID() + "." + suffix;
// 在uploadPath路径下创建名为fileName的文件对象
File file = new File(uploadPath,fileName);
// 生成文件
uploadFile.transferTo(file);
return "上传成功";
}
5.访问
localhost://127.0.0.1:端口/映射路径/文件.后缀