【web】springboot3 生成本地文件 url

流程

  • 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());
    }
}

相关推荐

  1. minio本地文件上传/远程url上传

    2024-01-10 13:32:01       37 阅读
  2. Android 生成Excel文件保存到本地

    2024-01-10 13:32:01       43 阅读
  3. SpringBoot映射URL访问本地文件,实现文件预览功能

    2024-01-10 13:32:01       35 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-10 13:32:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-10 13:32:01       100 阅读
  3. 在Django里面运行非项目文件

    2024-01-10 13:32:01       82 阅读
  4. Python语言-面向对象

    2024-01-10 13:32:01       91 阅读

热门阅读

  1. 用BEVformer来卷自动驾驶-3

    2024-01-10 13:32:01       102 阅读
  2. RabbitMq

    2024-01-10 13:32:01       65 阅读
  3. 155. 最小栈

    2024-01-10 13:32:01       55 阅读
  4. oracle常用内部表和视图

    2024-01-10 13:32:01       51 阅读
  5. 编程语言的未来

    2024-01-10 13:32:01       60 阅读
  6. Orchestrator源码解读3-故障处理阶段

    2024-01-10 13:32:01       64 阅读