springboot3生成本地文件url的实现示例
作者:灯笼只能来教室体验生活
本文主要介绍了springboot3生成本地文件url的实现示例,从而提供一种高效的文件管理方式,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
流程
- avatar_dir:请求图片在服务端的存放路径
- user.dir:项目根目录
效果
静态资源访问
application.yml
设置静态文件存储路径
custom: upload: avatar_dir: ${user.dir}/avatar_dir/ avatar_dir_name: avatar_dir
FileUploadConfig
application.yml 信息读取配置类
@Data @Configuration @ConfigurationProperties(prefix = "custom.upload") public class FileUploadConfig { private String avatarDir; private String avatarDirName; }
静态资源访问配置类
@Configuration public class WebConfig implements WebMvcConfigurer { @Autowired FileUploadConfig uploadConfig; @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { File file = new File(uploadConfig.getAvatarDir()); String path = "file:" + file + File.separator; // 匹配 http://ip:port/avatar_dir/ 下的所有文件 registry.addResourceHandler("/avatar_dir/**") // 实际静态文件地址 .addResourceLocations(path); } }
Service
@Service public interface FileService { // 获取图像 Url public Result<String> getImageUrl(User user, String host, int port); // 路径拼接 public String joinPaths(String... paths); }
ServiceImpl
http://ip:port/静态文件存储路径/文件名
String imageUrl = String.format( "http://%s:%d/%s", host, port, joinPaths( uploadConfig.getAvatarDirName(), avatar ) );
实现代码
@Service public class FileServiceImpl implements FileService { @Autowired FileUploadConfig uploadConfig; @Autowired IUserService userService; // 路径拼接 @Override public String joinPaths(String... paths) { Path resultPath = Paths.get(""); for (String path : paths) { resultPath = resultPath.resolve(path); } return resultPath.toString(); } // 判断文件是否存在 private Boolean isUserAvatarExists(String avatar) { String path = joinPaths(uploadConfig.getAvatarDir(), avatar); File filePath = new File(path); return filePath.exists(); } // 获取图像 Url @Override public Result<String> getImageUrl(User user, String host, int port) { // 用户头像的文件名唯一,并保存在了数据库中,avatar = xxx.png String avatar = this.userService.getById(user.getUserId()).getAvatar(); if (isUserAvatarExists(avatar)) { String imageUrl = String.format("http://%s:%d/%s", host, port, joinPaths(uploadConfig.getAvatarDirName(), avatar)); return Result.successfulResult("获取成功", imageUrl); } return Result.errorResult("文件丢失"); } }
Controller
@Tag(name = "文件上传接口") @RestController @RequestMapping("/sign/file") public class FileUploadController { @Autowired FileService fileService; @Operation(summary = "获取图片 URL") @PostMapping("/image/get") public Result<String> getImageUrl(@RequestBody User user) { URI currentUri = ServletUriComponentsBuilder.fromCurrentRequestUri().build().toUri(); // currentUri.getHost() 获取请求 IP,如 localhost // currentUri.getPort() 获取请求 端口号,如 8080 return fileService.getImageUrl(user, currentUri.getHost(), currentUri.getPort()); } }
到此这篇关于springboot3生成本地文件url的实现示例的文章就介绍到这了,更多相关springboot3生成本地文件url内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!