0


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

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

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

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

在浏览器直接输入:

  1. file:///+本地磁盘目录或者磁盘文件全路径

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

1、自定义配置类

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

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

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

自定义 file配置类:

  1. @Data@Component@ConfigurationProperties(prefix ="file")publicclassFileProperties{/**
  2. * 默认的存储桶名称
  3. */privateString bucketName ="bucketName";/**
  4. * 本地文件配置信息
  5. */privateLocalFileProperties local;}
  1. /**
  2. * 本地文件 配置信息
  3. */@Data@Component@ConfigurationProperties(prefix ="local")publicclassLocalFileProperties{/**
  4. * 是否开启
  5. */privateboolean enable;/**
  6. * 默认磁盘根路径
  7. */privateString basePath;/**
  8. * 默认文件URL前缀
  9. */privateString baseUrl;}

2、添加静态资源映射

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

  1. /**
  2. * WebMvc 配置类
  3. */@ConfigurationpublicclassWebMvcConfigimplementsWebMvcConfigurer{@AutowiredprivateFileProperties fileProperties;/**
  4. * 配置静态资源访问映射
  5. *
  6. * @param registry
  7. */@OverridepublicvoidaddResourceHandlers(ResourceHandlerRegistry registry){
  8. registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
  9. registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
  10. registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");// swagger-bootstrap-ui依赖
  11. registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");//本地文件上传路径
  12. registry.addResourceHandler("/profile/**")// 自定义URL访问前缀,和file配置一致.addResourceLocations(String.format("%s/%s/","file:", fileProperties.getLocal().getBasePath()));}}

3、前端通过 URL访问

本地文件:

在这里插入图片描述

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

在这里插入图片描述

– 求知若饥,虚心若愚。


本文转载自: https://blog.csdn.net/qq_42402854/article/details/139354271
版权归原作者 Charge8 所有, 如有侵权,请联系我们删除。

“SpringBoot前端URL访问本地磁盘文件”的评论:

还没有评论