オブジェクトを読み取る

このページでは、Cloud Storage バケットからアプリケーションのメモリに直接オブジェクト データを読み取る方法、またはウェブブラウザやコマンドライン ターミナルでインタラクティブに読み取る方法について説明します。オブジェクトをメモリに読み取るか、インタラクティブに読み取ることは、永続的なローカル ファイル システムにファイルを書き込むことに関連する CPU、ディスク I/O、レイテンシのオーバーヘッドを回避する方法でデータをストリーミング、検査、処理する場合におすすめします。

オブジェクトを永続ストレージまたはローカル ストレージにダウンロードする手順については、オブジェクトをダウンロードするをご覧ください。オブジェクトの読み取りとダウンロードのコンセプトの概要については、オブジェクトの読み取りとダウンロードをご覧ください。

必要なロール

オブジェクト データの読み取りに必要な権限を取得するには、次の IAM ロールを付与するよう管理者に依頼してください。

ロールの付与については、プロジェクト、フォルダ、組織へのアクセス権の管理をご覧ください。

ストレージ オブジェクト閲覧者(roles/storage.objectViewer)ロールには、オブジェクトの読み取りに必要な storage.objects.get 権限が含まれています。ストレージ管理者(roles/storage.admin)ロールには、storage.objects.get 権限に加えて、storage.buckets.list 権限と storage.buckets.get 権限が含まれています。これらの権限は、プロジェクト内のバケットを一覧表示し、バケットに関する情報を表示するために必要です。これらの権限を含むストレージ管理者(roles/storage.admin)ロールは、 Google Cloud コンソールを使用してオブジェクトをインタラクティブに読み取る場合にのみ必要です。

カスタムロールや他の事前定義ロールを使用して、これらの権限を取得することもできます。

バケットに対するロールを付与する手順については、バケットでの 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. [オブジェクトの詳細] ページで、オブジェクトの公開 URL または認証済み URL をクリックして、データを読み取ります。

コマンドライン

オブジェクトのバイト ペイロードをターミナル 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: 読み取るオブジェクトの URL エンコード名。例: pets%2Fdog.png として URL エンコードされている pets/dog.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: 読み取るオブジェクトの URL エンコード名。例: pets%2Fdog.png として URL エンコードされている pets/dog.png

次のステップ