文章目录 流程 效果 静态资源访问 Service ServiceImpl Controller
流程
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; registry. addResourceHandler ( "/avatar_dir/**" ) . addResourceLocations ( path) ; }
}
Service
@Service
public interface FileService { 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 ( ) ; } @Override public Result < String > getImageUrl ( User user, String host, int port) { 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 ( ) ; return fileService. getImageUrl ( user, currentUri. getHost ( ) , currentUri. getPort ( ) ) ; }
}