1.设置静态资源文件,在配置文件application.properties中
#单个文件最大100m
spring.servlet.multipart.max-file-size=100MB
#多个文件最大200m
spring.servlet.multipart.max-request-size=200MB
#把filePath设置为静态资源文件
spring.web.resources.static-locations=file:${filePath},classpath:static
#
filePath=d:/java/files
2.后端controller代码部分
@RestController
public class UploadController {
@Value("${filePath}")
private String dirPath;
@PostMapping("upload")
public String upload(MultipartFile file) throws IOException {
//得到上传图片的名称
String fileName = file.getOriginalFilename();
System.out.println(fileName);
//得到后缀.jpg
String suffix = fileName.substring(fileName.lastIndexOf("."));
//得到唯一的文件名, UUID.randomUUID()得到唯一标识符
fileName = UUID.randomUUID()+suffix;
System.out.println(fileName);
SimpleDateFormat simpleDateFormat =
new SimpleDateFormat("/yyyy/MM/dd/");
//得到日期相关的路径 /2023/7/12/
String datePath =simpleDateFormat.format(new Date());
//创建文件对象
File dirFile = new File(dirPath+datePath);
//判断如果文件不存在则创建
if(!dirFile.exists()){
dirFile.mkdirs();//创建文件夹
}
//把图片保存到指定路径 异常抛出
file.transferTo(new File(dirPath+datePath+fileName));
//把图片路径返回给前端
return datePath+fileName;
}
}