【web】springboot3 生成本地文件 url

2024-01-09 21:00:11

流程

  • avatar_dir:请求图片在服务端的存放路径
  • user.dir:项目根目录
    在这里插入图片描述

效果

在这里插入图片描述

静态资源访问

在这里插入图片描述

  1. application.yml
    设置静态文件存储路径
    custom:
      upload:
        avatar_dir: ${user.dir}/avatar_dir/
        avatar_dir_name: avatar_dir
    
  2. FileUploadConfig
    application.yml 信息读取配置类
    @Data
    @Configuration
    @ConfigurationProperties(prefix = "custom.upload")
    public class FileUploadConfig {
       private String avatarDir;
       private String avatarDirName;
    }
    
  3. 静态资源访问配置类
    @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());
    }
}

文章来源:https://blog.csdn.net/m0_52733659/article/details/135487992
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。