SpringBoot前端通过 URL访问本地磁盘文件,其实就是 SpringBoot访问web中的静态资源的处理方式。

SpringBoot 访问web中的静态资源:https://blog.csdn.net/qq_42402854/article/details/90295079

首先,我们知道浏览器访问本地磁盘文件的方式为:

在浏览器直接输入:file:///+本地磁盘目录或者磁盘文件全路径

我们只需要在 Spring Boot中配置静态资源的处理即可。

1、自定义配置类

将配置信息提取到配置文件,方便我们配置。

application.yml配置文件:自定义 file配置信息

# 文件上传相关
file:
  bucketName: def_bucket
  local:
    enable: true
#    base-path: /home/app/ws_demo/ws-files
    base-path: D:/ws-files/upload
    baseUrl: http://127.0.0.1:19090/ws/profile

自定义 file配置类:

@Data
@Component
@ConfigurationProperties(prefix = "file")
public class FileProperties {

	/**
	 * 默认的存储桶名称
	 */
	private String bucketName = "bucketName";

	/**
	 * 本地文件配置信息
	 */
	private LocalFileProperties local;

}
/**
 * 本地文件 配置信息
 */
@Data
@Component
@ConfigurationProperties(prefix = "local")
public class LocalFileProperties {

    /**
     * 是否开启
     */
    private boolean enable;

    /**
     * 默认磁盘根路径
     */
    private String basePath;

    /**
     * 默认文件URL前缀
     */
    private String baseUrl;

}

2、添加静态资源映射

在配置类中添加静态资源映射。

/**
 * WebMvc 配置类
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Autowired
    private FileProperties fileProperties;

    /**
     * 配置静态资源访问映射
     *
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");

        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
        //  swagger-bootstrap-ui依赖
        registry.addResourceHandler("doc.html")
                .addResourceLocations("classpath:/META-INF/resources/");

        //本地文件上传路径
        registry.addResourceHandler("/profile/**") // 自定义URL访问前缀,和file配置一致
                .addResourceLocations(String.format("%s/%s/", "file:", fileProperties.getLocal().getBasePath()));
    }

}

3、前端通过 URL访问

本地文件:

在这里插入图片描述

启动项目,浏览器访问 URL接口。

在这里插入图片描述

– 求知若饥,虚心若愚。

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐