上传文件
@PostMapping("/upload")
@ApiOperation("文件上传")
public String uploadImg(MultipartFile file){
if (file.isEmpty()) {
System.out.println("上传的文件为空!");
}
// 文件名
String fileName = file.getOriginalFilename();
// 获取文件后缀名
String extension = fileName.substring(fileName.indexOf("."));
// 上传文件的路径
String uploadFolder = "/tmp/nft/uploads/";
// 生成一个新的文件名
fileName = UUID.randomUUID() + extension;
File dest = new File(uploadFolder + fileName);
// 检测文件目录是否存在 不存在则创建
if (!dest.getParentFile().exists()){
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest);
} catch (IOException e) {
e.printStackTrace();
throw new CheckException("文件上传失败");
}
// 返回虚拟文件访问路径
return "/upload/" + fileName;
}
String uploadFolder = this.getClass().getResource("/").getPath() + "/uploads/";
String uploadFolder = "/tmp/nft/uploads/";
配置映射
@Configuration
public class UploadConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/upload/**").addResourceLocations("file:/tmp/nft/uploads/");
}
}
- file:/tmp/nft/uploads/: 映射到服务器目录
- classpath:uploads/:映射到资源目录