首页 > 编程语言 > 详细

SpringBoot如何加载文件资源

时间:2020-05-30 13:51:39      阅读:150      评论:0      收藏:0      [点我收藏+]
Spring Boot中加载静态资源
  • 静态资源等处在/resource/static文件夹下面,即在Spring Boot的默认存放文件路径下,无需做额外的配置,只需要通过服务名拼接static下的资源相对路径就可以访问,例如我Spring Boot项目中的下面配置
    server.port=8081
    server.servlet.context-path=/spring-boot-demo
    
    spring.application.name=spring-boot-demo
    
    这种情况下只需要通过“{ip}:{server.port}/{server.servlet.context-path}/{静态资源相对路径}”即可访问,例如我的项目中有以下几个文件

    技术分享图片

  

  static下有a.jpg和b.jpg文件,可以通过http://localhost:8081/spring-boot-demo/a.jpg,访问a.jpg
技术分享图片
 
技术分享图片
 
  • 静态文件不在/resource/static文件夹下面,例如我在resource下新添加了一个files文件夹,如下图
技术分享图片
 
  如果此时我需要访问files下的文件,同时也需要能够访问static下的文件,那么我的properties文件中的配置就需要做下改变
server.port=8081
server.servlet.context-path=/spring-boot-demo

spring.application.name=spring-boot-demo

spring.resources.static-locations=classpath:static/,classpath:files/

  通过spring.resources.static-locations指定静态资源的路径,将新建的files/路径添加进配置里,因为想要继续能够访问static下的文件,所以将默认的static也添加进去,否则会报错404,,访问c.jpg效果图如下

技术分享图片
 
  • 文件不存在resource下,存在于磁盘的其他位置,比如将d.jpg其放在F:\opt\data\files下面,那么同样的,将F:\opt\data\files加入spring.resources.static-locations配置中,不过这里需要做些变化,需要在路径前加上“file:”,也需要将路径中的“\”换成”/“,如下
技术分享图片
 
 
  上述方式通过在properties配置文件中进行配置完成的,我们也可以通过Java代码的方式去完成相应的配置,properties中可以不需要添加上述的配置,如
server.port=8081
server.servlet.context-path=/spring-boot-demo

spring.application.name=spring-boot-demo

  代码中实现WebMvcConfigurer,覆盖addResourceHandlers(ResourceHandlerRegistry registry)方法,如下

package com.demo.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**")
.addResourceLocations("classpath:static/")
.addResourceLocations("classpath:files/")
.addResourceLocations( "file:F:\\opt\\data\\files\\");
}
}
   也可以达到一样的效果。

SpringBoot如何加载文件资源

原文:https://www.cnblogs.com/dsxie/p/12992006.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!