讀取物件

本頁面說明如何直接將 Cloud Storage 值區中的物件資料讀取至應用程式記憶體,或在網路瀏覽器或指令列終端機中以互動方式讀取。如要串流、檢查或處理資料,並避免將檔案寫入持續性本機檔案系統時,產生 CPU、磁碟 I/O 和延遲時間的負擔,建議您將物件讀取至記憶體或以互動方式讀取。

如需將物件下載到永久或本機儲存空間的操作說明,請參閱「下載物件」。如需物件讀取和下載的概念總覽,請參閱物件讀取和下載

必要的角色

如要取得讀取物件資料所需的權限,請要求管理員授予您下列 IAM 角色:

  • bucket 的「Storage 物件檢視者」 (roles/storage.objectViewer)
  • 儲存空間管理員 (roles/storage.admin) 專案 (使用 Google Cloud 控制台讀取物件資料時才需要)

如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和組織的存取權」。

Storage 物件檢視者 (roles/storage.objectViewer) 角色包含 storage.objects.get 權限,這是讀取物件的必要權限。除了 storage.objects.get 權限外,儲存空間管理員 (roles/storage.admin) 角色還具備 storage.buckets.liststorage.buckets.get 權限。您必須具備這些權限,才能列出專案中的值區,並查看值區的相關資訊。只有在想使用 Google Cloud 控制台以互動方式讀取物件時,才需要具備這些權限的「Storage 管理員」(roles/storage.admin) 角色。

您或許還可透過自訂角色或其他預先定義的角色取得這些權限。

如需授予 bucket 角色的操作說明,請參閱「在 bucket 上設定及管理 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 bucket」頁面。

    前往「Buckets」(值區) 頁面

  2. 在 bucket 清單中,點選要查看內容的 bucket 名稱。

  3. 在「物件」分頁中,按一下要讀取的物件名稱。

  4. 在「物件詳細資料」頁面中,按一下物件的公開網址或已驗證網址,即可讀取資料。

指令列

如要將物件的位元組酬載直接串流至終端機 stdout,請使用 gcloud storage cat 指令:

gcloud storage cat gs://BUCKET_NAME/OBJECT_NAME

更改下列內容:

  • BUCKET_NAME:包含要讀取物件的 bucket 名稱。例如: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.googleapis.com/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 物件要求呼叫 XML API

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

    更改下列內容:

    • BUCKET_NAME:包含要讀取物件的值區名稱。例如:my-bucket

    • OBJECT_NAME:您要讀取的物件名稱 (經過網址編碼)。例如 pets/dog.png,網址編碼為 pets%2Fdog.png

後續步驟