Spring boot 读取静态文件

本文探讨了在不同环境下加载静态资源的方法,特别是在Linux系统中使用Java进行资源文件读取的两种常见方式,包括使用ResourceUtils和ClassPathResource。这些方法对于解决跨平台资源加载问题具有实际意义。

1、File jsFileName = ResourceUtils.getFile("classpath:static/js/jsCode.js");//这种方法在linux(未测试)下无法工作
 

2、Resource resource = new ClassPathResource("static/js/jsCode.js");
   File jsFileName =  resource.getFile();
### 如何在Spring Boot 3中读取静态文件Spring Boot 3中,读取静态文件是一个常见的需求。默认情况下,Spring Boot会自动配置静态资源路径,这些路径通常位于`src/main/resources/static/`目录下[^1]。 #### 配置静态文件路径 如果需要自定义静态文件的位置,可以通过修改`application.properties`或`application.yml`来实现: ```properties # application.properties spring.resources.static-locations=classpath:/custom-static/,classpath:/another-location/ ``` 或者通过YAML格式: ```yaml # application.yml spring: resources: static-locations: classpath:/custom-static/,classpath:/another-location/ ``` 上述配置允许开发者指定多个静态资源位置[^4]。 #### 访问静态文件静态文件被放置到正确的路径后,默认可以通过应用的根URL访问它们。例如,假设有一个名为`example.html`的文件存放在`static`目录下,则可通过以下方式访问它: ``` http://localhost:8080/example.html ``` 对于更复杂的场景,比如返回特定类型的静态文件(如图片、PDF等),可以编写控制器方法并利用`ResourceLoader`类加载文件: ```java import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController public class FileController { private final ResourceLoader resourceLoader; public FileController(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } @GetMapping("/files/{filename}") public ResponseEntity<Resource> serveFile(@PathVariable String filename) throws Exception { Resource file = resourceLoader.getResource("classpath:static/" + filename); return ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"") .body(file); } } ``` 此代码片段展示了如何动态地从`static`目录中提供文件下载服务。 #### 安全性考虑 为了保护某些敏感的静态资源不被未经授权的用户访问,在实际项目中可能还需要集成Spring Security来进行权限控制[^2]。例如,仅允许经过身份验证的用户获取特定文件夹下的内容。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值