You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CloudRun部署Spring Boot应用后文件读取与放置位置咨询

解决SpringBoot部署到CloudRun后文件读取失败的问题

问题原因

本地运行时,代码直接读取项目根目录的文件,当前工作目录正好对应项目根目录,所以能正常找到文件。但部署到CloudRun后,SpringBoot项目会被打包成Jar包,项目内的文件会被封装到Jar内部,FileInputStream只能读取磁盘上的独立文件,无法访问Jar包内的资源,因此出现"File not Found"错误。

解决方法

方法一:将文件打包到Jar中(适合静态文件)

把Legend.jpg放到项目的src/main/resources目录下,然后用类加载器读取资源,这种方式在本地和CloudRun环境都能正常工作:

// 非静态方法中使用
InputStream is = getClass().getResourceAsStream("/Legend.jpg");

// 静态方法中使用,替换YourClass为你的类名
InputStream is = YourClass.class.getResourceAsStream("/Legend.jpg");

注意路径开头的/代表resources目录的根,确保文件名和大小写完全匹配。

方法二:使用Cloud Storage存储文件(适合动态修改的文件)

如果文件需要后续更新,不适合打包到Jar中,可以用GCP Cloud Storage存储文件:

  1. 在GCP控制台创建Cloud Storage Bucket,上传Legend.jpg
  2. 给CloudRun的服务账号添加Storage Object Viewer权限,确保服务能读取Bucket中的文件
  3. 在SpringBoot项目中引入GCP Storage依赖(Maven示例):
<dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>spring-cloud-gcp-starter-storage</artifactId>
</dependency>
  1. 读取文件的代码示例:
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.Storage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class FileService {
    @Autowired
    private Storage storage;

    public InputStream getLegendImage() {
        // 替换为你的Bucket名称
        Blob blob = storage.get("your-bucket-name", "Legend.jpg");
        return blob.getContent();
    }
}

内容的提问来源于stack exchange,提问作者prathibha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 13:55:40