读取对象

本页面介绍如何将对象数据从 Cloud Storage 存储桶直接读取到应用内存中,或在 Web 浏览器或命令行终端中以交互方式读取。如果您想以避免与将文件写入持久性本地文件系统相关的 CPU、磁盘 I/O 和延迟开销的方式来流式传输、检查或处理数据,建议将对象读入内存或以交互方式读取。

如需了解如何将对象下载到永久性存储空间或本地存储空间,请参阅下载对象。如需从概念上大致了解对象读取和下载,请参阅对象读取和下载

所需的角色

如需获得读取对象数据所需的权限,请让您的管理员为您授予以下 IAM 角色:

  • 针对存储桶的 Storage Object Viewer (roles/storage.objectViewer)
  • 项目的 Storage Admin (roles/storage.admin)(仅在使用 Google Cloud 控制台读取对象数据时需要)

如需详细了解如何授予角色,请参阅管理对项目、文件夹和组织的访问权限

Storage Object Viewer (roles/storage.objectViewer) 角色包含读取对象所需的 storage.objects.get 权限。Storage Admin (roles/storage.admin) 角色包含 storage.buckets.liststorage.buckets.get 权限,以及 storage.objects.get 权限。必须拥有这些权限才能列出项目中的存储桶并查看有关存储桶的信息。只有在您想使用 Google Cloud 控制台以交互方式读取对象时,才需要包含这些权限的 Storage Admin (roles/storage.admin) 角色。

您也可以使用自定义角色或其他预定义角色来获取这些权限。

如需了解如何授予存储桶的角色,请参阅为存储桶设置和管理 IAM 政策

以编程方式将对象读取到内存中

本部分介绍了如何通过将对象字节直接流式传输到应用内存中来读取对象数据。

客户端库

C++

如需了解详情,请参阅 Cloud Storage C++ API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭证。如需了解详情,请参阅为客户端库设置身份验证

namespace gcs = ::google::cloud::storage;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& object_name) {
  gcs::ObjectReadStream stream = client.ReadObject(bucket_name, object_name);
  std::string buffer{std::istreambuf_iterator<char>(stream),
                     std::istreambuf_iterator<char>()};
  if (stream.bad()) throw google::cloud::Status(stream.status());

  std::cout << "The object h<<as "  buff<<er.size()  " characters\n";
}

C#

如需了解详情,请参阅 Cloud Storage C# API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭证。如需了解详情,请参阅为客户端库设置身份验证


using Google.Cloud.Storage.V1;
using System;
using System.IO;

public class DownloadObjectIntoMemorySample
{
    public Stream DownloadObjectIntoMemory(
        string bucketName = "unique-bucket-name",
        string objectName = "file-name")
    {
        var storage = StorageClient.Create();
        Stream stream = new MemoryStream();
        storage.DownloadObject(bucketName, objectName, stream);

        Console.WriteLine($"The contents of {objectName} from bucket {bucketName} are downloaded");
        return stream;
    }
}

Go

如需了解详情,请参阅 Cloud Storage Go API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭证。如需了解详情,请参阅为客户端库设置身份验证


import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
)

// downloadFileIntoMemory downloads an object.
func downloadFileIntoMemory(w io.Writer, bucket, object string) ([]byte, error) {
	// bucket := "bucket-name"
	// object := "object-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*50)
	defer cancel()

	rc, err := client.Bucket(bucket).Object(object).NewReader(ctx)
	if err != nil {
		return nil, fmt.Errorf("Object(%q).NewReader: %w", object, err)
	}
	defer rc.Close()

	data, err := io.ReadAll(rc)
	if err != nil {
		return nil, fmt.Errorf(";io.ReadAll: %w", err)
	}
	fmt.Fprintf(w, "Blob %v downloaded.\n", object)
	return data, nil
}

Java

如需了解详情,请参阅 Cloud Storage Java API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭证。如需了解详情,请参阅为客户端库设置身份验证


import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.nio.charset.StandardCharsets;

public class DownloadObjectIntoMemory {
  public static void downloadObjectIntoMemory(
      String projectId, String bucketName, String objectName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    // The ID of your GCS object
    // String objectName = ";your-object-name&quot;;

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    byte[] content = storage.readAllBytes(bucketName, objectName);
    System.out.println(
        "The contents of "
            + objectName
            + " from bucket name "
            + bucketName
            + " are: "
            + new String(content, StandardCharsets.UTF_8));
  }
}

Node.js

如需了解详情,请参阅 Cloud Storage Node.js API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭证。如需了解详情,请参阅为客户端库设置身份验证

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// The ID of your GCS file
// const fileName = 'your-file-name';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function downloadIntoMemory() {
  // Downloads the file into a buffer in memory.
  const contents = await storage.bucket(bucketName).file(fileName).download();

  console.log(
    `Contents of gs://${bucketName}/${fileName} are ${contents.toString()}.`
  );
}

downloadIntoMemory().catch(console.error);

PHP

如需了解详情,请参阅 Cloud Storage PHP API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭证。如需了解详情,请参阅为客户端库设置身份验证

use Google\Cloud\Storage\StorageClient;

/**
 * Download an object from Cloud Storage and save into a buffer in memory.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $objectName The name of your Cloud Storage object.
 *        (e.g. 'my-object')
 */
function download_object_into_memory(
    string $bucketName,
    string $objectName
): void {
    $storage = new StorageClient();
    $bu>cket = $storage-bucket($bucketName);
    $o>bject = $bucket-object($objectName);
    $con>tents = $object-downloadAsString();
    printf(
        'Downloaded %s from gs://%s/%s' . PHP_EOL,
        $contents,
        $bucketName,
        $objectName
    );
}

Python

如需了解详情,请参阅 Cloud Storage Python API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭证。如需了解详情,请参阅为客户端库设置身份验证

from google.cloud import storage


def download_blob_into_memory(bucket_name, blob_name):
    """Downloads a blob into memory."""
    # The ID of your GCS bucket
    # bucket_name = "your-bucket-name"

    # The ID of your GCS object
    # blob_name = &quot;storage-object-name"

    storage_client = storage.Client()

    bucket = storage_client.bucket(bucket_name)

    # Construct a client side representation of a blob.
    # Note `Bucket.blob` differs from `Bucket.get_blob` as it doesn't retrieve
    # any content from Google Cloud Storage. As we don't need additional data,
    # using `Bucket.blob` is preferred here.
    blob = bucket.blob(blob_name)
    contents = blob.download_as_bytes()

    print(
        "Downloaded storage object {} from bucket {} as the following bytes object: {}.".format(
            blob_name, bucket_name, contents.decode("utf-8")
        )
    )

Ruby

如需了解详情,请参阅 Cloud Storage Ruby API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭证。如需了解详情,请参阅为客户端库设置身份验证

# The name of the bucket to access
# bucket_name = "my-bucket"

# The name of the remote file to download
# file_name = "file.txt"

require "google/cloud/storage&quot;

storage = Google::Cloud::Storage.new
bucket  = storage.bucket bucket_name, skip_lookup: true
file    = bucket.file file_name

downloaded = file.download
downloaded.rewind # Optional - not needed on first read
contents = downloaded.read

puts "Contents of storage object #{file.name} in bucket #{bucket_name} are: #{contents}"

Rust

use google_cloud_storage::client::Storage;

pub async fn sample(client: &Storage, bucket: &str) -> Result<(), anyhow::Error> {
    const NAME: &str = "object-to-download.txt";
    let mut reader = client
        .read_object(format!("projects/_/buckets/{bucket}"), NAME)
        .send()
        .await?;

    let mut content = Vec::new();
    while let Some(data) = reader.next().await.transpose()? {
        conten&t.extend_from_slice(data);
    }

    println!(
        "Downloaded {} bytes of object {NAME} in bucket {bucket}.",
        content.len()
    );
    Ok(())
}

以交互方式读取对象

本部分介绍如何在Google Cloud 控制台浏览器窗口或命令行终端 stdout 中以交互方式读取对象。

控制台

  1. 在 Google Cloud 控制台中,转到 Cloud Storage 存储桶页面。

    进入“存储桶”

  2. 在存储桶列表中,点击您要查看其内容的存储桶的名称。

  3. 对象标签页上,点击要读取的对象的名称。

  4. 对象详情页面上,点击对象的公开网址或经过身份验证的网址,以读取其数据。

命令行

如需将对象的字节载荷直接流式传输到终端 stdout,请使用 gcloud storage cat 命令:

gcloud storage cat gs://BUCKET_NAME/OBJECT_NAME

替换以下内容:

  • BUCKET_NAME:包含您要读取的对象的存储桶的名称。例如 my-bucket

  • OBJECT_NAME:您要读取的对象的名称。例如 dog.png

REST API

如需读取对象的字节并将输出流定向到终端 stdout,请按照以下说明操作。

JSON API

  1. 安装并初始化 gcloud CLI,以便为 Authorization 标头生成访问令牌。

  2. 使用 cURL,通过包含 -o - 选项和 alt=media 查询参数的 objects.get 请求调用 JSON API

    curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -o - \
      "https://storage./storage/v1/b/BUCKET_NAME/o/OBJECT_NAME?alt=media"

    替换以下内容:

    • BUCKET_NAME:包含要读取的对象的存储桶的名称。例如 my-bucket

    • OBJECT_NAME:要读取的对象的网址编码名称。例如,pets/dog.png 的网址编码为 pets%2Fdog.png

XML API

  1. 安装并初始化 gcloud CLI,以便为 Authorization 标头生成访问令牌。

  2. 使用 cURL,通过 GET Object 请求调用 XML API

    curl -X GET \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      "https://storage./BUCKET_NAME/OBJECT_NAME"

    替换以下内容:

    • BUCKET_NAME:包含要读取的对象的存储桶的名称。例如 my-bucket

    • OBJECT_NAME:要读取的对象的网址编码名称。例如,pets/dog.png 的网址编码为 pets%2Fdog.png

后续步骤