객체 읽기

이 페이지에서는 Cloud Storage 버킷에서 애플리케이션 메모리로 직접 또는 웹브라우저나 명령줄 터미널에서 대화형으로 객체 데이터를 읽는 방법을 설명합니다. 객체를 메모리로 읽거나 대화형으로 읽는 것은 영구 로컬 파일 시스템에 파일을 쓰는 것과 관련된 CPU, 디스크 I/O, 지연 시간 오버헤드를 방지하는 방식으로 데이터를 스트리밍, 검사 또는 처리하려는 경우에 권장됩니다.

객체를 영구 또는 로컬 저장소에 다운로드하는 방법은 객체 다운로드를 참고하세요. 객체 읽기 및 다운로드의 개념 개요는 객체 읽기 및 다운로드를 참고하세요.

필요한 역할

객체 데이터를 읽는 데 필요한 권한을 얻으려면 관리자에게 다음 IAM 역할을 부여해 달라고 요청하세요.

역할 부여에 대한 자세한 내용은 프로젝트, 폴더, 조직에 대한 액세스 관리를 참조하세요.

스토리지 객체 뷰어 (roles/storage.objectViewer) 역할에는 객체를 읽는 데 필요한 storage.objects.get 권한이 포함되어 있습니다. 스토리지 관리자 (roles/storage.admin) 역할에는 storage.objects.get 권한 외에도 storage.buckets.liststorage.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. Authorization 헤더에 대한 액세스 토큰을 생성하려면 gcloud CLI가 설치 및 초기화되어 있어야 합니다.

  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/dog.pngpets%2Fdog.png로 URL 인코딩됩니다.

XML API

  1. Authorization 헤더에 대한 액세스 토큰을 생성하려면 gcloud CLI가 설치 및 초기화되어 있어야 합니다.

  2. cURL을 사용하여 GET 객체 요청으로 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/dog.pngpets%2Fdog.png로 URL 인코딩됩니다.

다음 단계