使用 Cloud Storage

您可以使用 Cloud Storage 来存储和提供文件,例如电影、图片或其他静态内容。

本文档介绍了如何在应用中使用 Google Cloud 客户端库将数据存储在 Cloud Storage 中,以及如何从 Cloud Storage 检索数据。

准备工作

  • 请按照 App Engine Java 版“Hello, World!”中的说明设置您的环境和项目,并了解如何在 App Engine 中设计 Java 应用的结构。记录并保存项目 ID,因为您需要用它来运行本文档中介绍的示例应用。

  • 请务必调用以下命令,为您的应用创建 Cloud Storage 存储分区:

    gsutil mb gs://[YOUR_BUCKET_NAME]
    
  • 将此存储分区设为可公开读取,以便其可以传送文件:

    gsutil defacl set public-read gs://[YOUR_BUCKET_NAME]
    

下载示例

如需克隆代码库,请执行以下命令:

git clone https://github.com/GoogleCloudPlatform/java-docs-samples
cd java-docs-samples/flexible/cloudstorage

修改项目配置并安装依赖项

app.yaml 中,将 BUCKET_NAME 设置为您之前为项目创建的 Cloud Storage。

runtime: java
env: flex

handlers:
- url: /.*
  script: this field is required, but ignored

env_variables:
  BUCKET_NAME: YOUR-BUCKET-NAME

pom.xml 中,添加 com.google.cloud 作为依赖项,并将 google-cloud-storage 指定为该依赖项的工件 ID;它提供了使用 Cloud Storage 所需的功能。

<!--  Using libraries-bom to manage versions.
See https://github.com/GoogleCloudPlatform/cloud-opensource-java/wiki/The-Google-Cloud-Platform-Libraries-BOM -->
<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>libraries-bom</artifactId>
      <version>25.0.0</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

<dependencies>
  <dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-storage</artifactId>
  </dependency>
</dependencies>

应用代码

示例应用会显示一个网页,提示用户提供要存储在 Cloud Storage 中的文件。在用户选择文件并点击“提交”后,doPost 请求处理程序会通过 Storage.create 将该文件写入 Cloud Storage 存储分区。

请注意,要从 Cloud Storage 中检索此文件,您需要指定存储分区名称和文件名。您应将这些值存储在应用中以备将来使用。

@SuppressWarnings("serial")
@WebServlet(name = "upload", value = "/upload")
@MultipartConfig()
public class UploadServlet extends HttpServlet {

  private static final String BUCKET_NAME = System.getenv("BUCKET_NAME");
  private static Storage storage = null;

  @Override
  public void init() {
    storage = StorageOptions.getDefaultInstance().getService();
  }

  @Override
  public void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws IOException, ServletException {
    final Part filePart = req.getPart("file");
    final String fileName = filePart.getSubmittedFileName();

    // Modify access list to allow all users with link to read file
    List<Acl> acls = new ArrayList<>();
    acls.add(Acl.of(Acl.User.ofAllUsers(), Acl.Role.READER));
    // the inputstream is closed by default, so we don't need to close it here
    Blob blob =
        storage.create(
            BlobInfo.newBuilder(BUCKET_NAME, fileName).setAcl(acls).build(),
            filePart.getInputStream());

    // return the public download link
    resp.getWriter().print(blob.getMediaLink());
  }
}

了解详情

如需全面了解 Cloud Storage,请参阅 Cloud Storage 文档