您的位置:首页 > 健康 > 美食 > SpringBoot前端URL访问本地磁盘文件

SpringBoot前端URL访问本地磁盘文件

2024/10/6 4:08:50 来源:https://blog.csdn.net/qq_42402854/article/details/139354271  浏览:    关键词:SpringBoot前端URL访问本地磁盘文件

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_bucketlocal:enable: true
#    base-path: /home/app/ws_demo/ws-filesbase-path: D:/ws-files/uploadbaseUrl: 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 {@Autowiredprivate FileProperties fileProperties;/*** 配置静态资源访问映射** @param registry*/@Overridepublic 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接口。

在这里插入图片描述

– 求知若饥,虚心若愚。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com