객체 다운로드

이 페이지에서는 Cloud Storage의 버킷에서 영구 스토리지로 객체를 다운로드하는 방법을 보여줍니다. 객체를 메모리로 다운로드할 수도 있습니다.

필요한 역할

객체를 다운로드하는 데 필요한 권한을 얻으려면 관리자에게 버킷에 대한 스토리지 객체 뷰어(roles/storage.objectViewer) 역할을 부여해 달라고 요청하세요. Google Cloud 콘솔을 사용하려는 경우 관리자에게 대신 버킷의 스토리지 관리자(roles/storage.admin) 역할을 부여해 달라고 요청하세요.

이러한 역할에는 객체를 다운로드하는 데 필요한 권한이 포함되어 있습니다. 필요한 정확한 권한을 보려면 필수 권한 섹션을 확장하세요.

필수 권한

  • storage.buckets.list
    • 이 권한은 Google Cloud 콘솔을 사용하여 이 페이지의 태스크를 수행할 때만 필요합니다.
  • storage.objects.get
  • storage.objects.list
    • 이 권한은 Google Cloud 콘솔을 사용하여 이 페이지의 태스크를 수행할 때만 필요합니다.

다른 사전 정의된 역할이나 커스텀 역할을 사용하여 이 권한을 부여받을 수도 있습니다.

버킷에 대한 역할 부여는 버킷에 IAM 사용을 참조하세요.

버킷에서 객체 다운로드

버킷에서 객체를 다운로드하려면 다음 안내를 따르세요.

콘솔

  1. Google Cloud 콘솔에서 Cloud Storage 버킷 페이지로 이동합니다.

    버킷으로 이동

  2. 버킷 목록에서 다운로드하려는 객체가 포함된 버킷 이름을 클릭합니다.

    객체 탭이 선택된 상태로 버킷 세부정보 페이지가 열립니다.

  3. 객체(폴더에 있을 수 있음)로 이동합니다.

  4. 객체와 연결된 다운로드 아이콘을 클릭합니다.

    브라우저 설정은 객체의 다운로드 위치를 제어합니다.

Google Cloud 콘솔에서 실패한 Cloud Storage 작업에 대한 자세한 오류 정보를 가져오는 방법은 문제 해결을 참조하세요.

명령줄

gcloud storage cp 명령어를 사용합니다.

gcloud storage cp gs://BUCKET_NAME/OBJECT_NAME SAVE_TO_LOCATION

각 항목의 의미는 다음과 같습니다.

  • BUCKET_NAME은 다운로드할 객체가 포함된 버킷의 이름입니다. 예를 들면 my-bucket입니다.

  • OBJECT_NAME은 다운로드할 객체의 이름입니다. 예를 들면 pets/dog.png입니다.

  • SAVE_TO_LOCATION은 객체를 저장할 로컬 경로입니다. 예를 들면 Desktop/Images입니다.

성공하면 응답은 다음 예와 같습니다.

Completed files 1/1 | 164.3kiB/164.3kiB

다운로드가 완료되기 전에 중단된 경우 동일한 cp 명령어를 실행하여 다운로드가 중단된 지점부터 다운로드를 재개합니다.

클라이언트 라이브러리

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);

  int count = 0;
  std::string line;
  while (std::getline(stream, line, '\n')) {
    ++count;
  }
  if (stream.bad()) throw google::cloud::Status(stream.status());

  std::cout << "The object has " << count << " lines\n";
}

C#

자세한 내용은 Cloud Storage C# API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


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

public class DownloadFileSample
{
    public void DownloadFile(
        string bucketName = "your-unique-bucket-name",
        string objectName = "my-file-name",
        string localPath = "my-local-path/my-file-name")
    {
        var storage = StorageClient.Create();
        using var outputFile = File.OpenWrite(localPath);
        storage.DownloadObject(bucketName, objectName, outputFile);
        Console.WriteLine($"Downloaded {objectName} to {localPath}.");
    }
}

Go

자세한 내용은 Cloud Storage Go API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

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

// downloadFile downloads an object to a file.
func downloadFile(w io.Writer, bucket, object string, destFileName string) error {
	// bucket := "bucket-name"
	// object := "object-name"
	// destFileName := "file.txt"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

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

	f, err := os.Create(destFileName)
	if err != nil {
		return fmt.Errorf("os.Create: %w", err)
	}

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

	if _, err := io.Copy(f, rc); err != nil {
		return fmt.Errorf("io.Copy: %w", err)
	}

	if err = f.Close(); err != nil {
		return fmt.Errorf("f.Close: %w", err)
	}

	fmt.Fprintf(w, "Blob %v downloaded to local file %v\n", object, destFileName)

	return nil

}

Java

자세한 내용은 Cloud Storage Java API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.nio.file.Paths;

public class DownloadObject {
  public static void downloadObject(
      String projectId, String bucketName, String objectName, String destFilePath) {
    // 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";

    // The path to which the file should be downloaded
    // String destFilePath = "/local/path/to/file.txt";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();

    Blob blob = storage.get(BlobId.of(bucketName, objectName));
    blob.downloadTo(Paths.get(destFilePath));

    System.out.println(
        "Downloaded object "
            + objectName
            + " from bucket name "
            + bucketName
            + " to "
            + destFilePath);
  }
}

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';

// The path to which the file should be downloaded
// const destFileName = '/local/path/to/file.txt';

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

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

async function downloadFile() {
  const options = {
    destination: destFileName,
  };

  // Downloads the file
  await storage.bucket(bucketName).file(fileName).download(options);

  console.log(
    `gs://${bucketName}/${fileName} downloaded to ${destFileName}.`
  );
}

downloadFile().catch(console.error);

다음 샘플은 여러 프로세스를 사용하여 여러 객체를 다운로드합니다.

/**
 * 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 the first GCS file to download
// const firstFileName = 'your-first-file-name';

// The ID of the second GCS file to download
// const secondFileName = 'your-second-file-name;

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

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

// Creates a transfer manager client
const transferManager = new TransferManager(storage.bucket(bucketName));

async function downloadManyFilesWithTransferManager() {
  // Downloads the files
  await transferManager.downloadManyFiles([firstFileName, secondFileName]);

  for (const fileName of [firstFileName, secondFileName]) {
    console.log(`gs://${bucketName}/${fileName} downloaded to ${fileName}.`);
  }
}

downloadManyFilesWithTransferManager().catch(console.error);

다음 샘플은 여러 프로세스를 사용하여 공통 프리픽스가 있는 모든 객체를 다운로드합니다.

/**
 * 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 the GCS folder to download. The folder will be downloaded to the local path of the executing code.
// const folderName = 'your-folder-name';

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

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

// Creates a transfer manager client
const transferManager = new TransferManager(storage.bucket(bucketName));

async function downloadFolderWithTransferManager() {
  // Downloads the folder
  await transferManager.downloadManyFiles(folderName);

  console.log(
    `gs://${bucketName}/${folderName} downloaded to ${folderName}.`
  );
}

downloadFolderWithTransferManager().catch(console.error);

PHP

자세한 내용은 Cloud Storage PHP API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

use Google\Cloud\Storage\StorageClient;

/**
 * Download an object from Cloud Storage and save it as a local file.
 *
 * @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')
 * @param string $destination The local destination to save the object.
 *        (e.g. '/path/to/your/file')
 */
function download_object(string $bucketName, string $objectName, string $destination): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $object->downloadToFile($destination);
    printf(
        'Downloaded gs://%s/%s to %s' . PHP_EOL,
        $bucketName,
        $objectName,
        basename($destination)
    );
}

Python

자세한 내용은 Cloud Storage Python API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

다음 샘플은 개별 객체를 다운로드합니다.

from google.cloud import storage


def download_blob(bucket_name, source_blob_name, destination_file_name):
    """Downloads a blob from the bucket."""
    # The ID of your GCS bucket
    # bucket_name = "your-bucket-name"

    # The ID of your GCS object
    # source_blob_name = "storage-object-name"

    # The path to which the file should be downloaded
    # destination_file_name = "local/path/to/file"

    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(source_blob_name)
    blob.download_to_filename(destination_file_name)

    print(
        "Downloaded storage object {} from bucket {} to local file {}.".format(
            source_blob_name, bucket_name, destination_file_name
        )
    )

다음 샘플은 여러 프로세스를 사용하여 여러 객체를 다운로드합니다.

def download_many_blobs_with_transfer_manager(
    bucket_name, blob_names, destination_directory="", workers=8
):
    """Download blobs in a list by name, concurrently in a process pool.

    The filename of each blob once downloaded is derived from the blob name and
    the `destination_directory `parameter. For complete control of the filename
    of each blob, use transfer_manager.download_many() instead.

    Directories will be created automatically as needed to accommodate blob
    names that include slashes.
    """

    # The ID of your GCS bucket
    # bucket_name = "your-bucket-name"

    # The list of blob names to download. The names of each blobs will also
    # be the name of each destination file (use transfer_manager.download_many()
    # instead to control each destination file name). If there is a "/" in the
    # blob name, then corresponding directories will be created on download.
    # blob_names = ["myblob", "myblob2"]

    # The directory on your computer to which to download all of the files. This
    # string is prepended (with os.path.join()) to the name of each blob to form
    # the full path. Relative paths and absolute paths are both accepted. An
    # empty string means "the current working directory". Note that this
    # parameter allows accepts directory traversal ("../" etc.) and is not
    # intended for unsanitized end user input.
    # destination_directory = ""

    # The maximum number of processes to use for the operation. The performance
    # impact of this value depends on the use case, but smaller files usually
    # benefit from a higher number of processes. Each additional process occupies
    # some CPU and memory resources until finished. Threads can be used instead
    # of processes by passing `worker_type=transfer_manager.THREAD`.
    # workers=8

    from google.cloud.storage import Client, transfer_manager

    storage_client = Client()
    bucket = storage_client.bucket(bucket_name)

    results = transfer_manager.download_many_to_path(
        bucket, blob_names, destination_directory=destination_directory, max_workers=workers
    )

    for name, result in zip(blob_names, results):
        # The results list is either `None` or an exception for each blob in
        # the input list, in order.

        if isinstance(result, Exception):
            print("Failed to download {} due to exception: {}".format(name, result))
        else:
            print("Downloaded {} to {}.".format(name, destination_directory + name))

다음 샘플은 여러 프로세스를 사용하여 버킷의 모든 객체를 다운로드합니다.

def download_bucket_with_transfer_manager(
    bucket_name, destination_directory="", workers=8, max_results=1000
):
    """Download all of the blobs in a bucket, concurrently in a process pool.

    The filename of each blob once downloaded is derived from the blob name and
    the `destination_directory `parameter. For complete control of the filename
    of each blob, use transfer_manager.download_many() instead.

    Directories will be created automatically as needed, for instance to
    accommodate blob names that include slashes.
    """

    # The ID of your GCS bucket
    # bucket_name = "your-bucket-name"

    # The directory on your computer to which to download all of the files. This
    # string is prepended (with os.path.join()) to the name of each blob to form
    # the full path. Relative paths and absolute paths are both accepted. An
    # empty string means "the current working directory". Note that this
    # parameter allows accepts directory traversal ("../" etc.) and is not
    # intended for unsanitized end user input.
    # destination_directory = ""

    # The maximum number of processes to use for the operation. The performance
    # impact of this value depends on the use case, but smaller files usually
    # benefit from a higher number of processes. Each additional process occupies
    # some CPU and memory resources until finished. Threads can be used instead
    # of processes by passing `worker_type=transfer_manager.THREAD`.
    # workers=8

    # The maximum number of results to fetch from bucket.list_blobs(). This
    # sample code fetches all of the blobs up to max_results and queues them all
    # for download at once. Though they will still be executed in batches up to
    # the processes limit, queueing them all at once can be taxing on system
    # memory if buckets are very large. Adjust max_results as needed for your
    # system environment, or set it to None if you are sure the bucket is not
    # too large to hold in memory easily.
    # max_results=1000

    from google.cloud.storage import Client, transfer_manager

    storage_client = Client()
    bucket = storage_client.bucket(bucket_name)

    blob_names = [blob.name for blob in bucket.list_blobs(max_results=max_results)]

    results = transfer_manager.download_many_to_path(
        bucket, blob_names, destination_directory=destination_directory, max_workers=workers
    )

    for name, result in zip(blob_names, results):
        # The results list is either `None` or an exception for each blob in
        # the input list, in order.

        if isinstance(result, Exception):
            print("Failed to download {} due to exception: {}".format(name, result))
        else:
            print("Downloaded {} to {}.".format(name, destination_directory + name))

Ruby

자세한 내용은 Cloud Storage Ruby API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

def download_file bucket_name:, file_name:, local_file_path:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  # The ID of your GCS object
  # file_name = "your-file-name"

  # The path to which the file should be downloaded
  # local_file_path = "/local/path/to/file.txt"

  require "google/cloud/storage"

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

  file.download local_file_path

  puts "Downloaded #{file.name} to #{local_file_path}"
end

REST API

JSON API

  1. OAuth 2.0 Playground에서 승인 액세스 토큰을 가져옵니다. 자체 OAuth 사용자 인증 정보를 사용하도록 Playground를 구성합니다. 자세한 내용은 API 인증을 참조하세요.
  2. cURL을 사용하여 GET 객체 요청으로 JSON API를 호출합니다.

    curl -X GET \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      -o "SAVE_TO_LOCATION" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/o/OBJECT_NAME?alt=media"

    각 항목의 의미는 다음과 같습니다.

    • OAUTH2_TOKEN은 1단계에서 생성한 액세스 토큰입니다.
    • SAVE_TO_LOCATION은 객체를 저장할 위치의 경로입니다. 예를 들면 Desktop/dog.png입니다.
    • BUCKET_NAME은 다운로드할 객체가 포함된 버킷의 이름입니다. 예: my-bucket
    • OBJECT_NAME은 다운로드할 객체의 URL 인코딩 이름입니다. 예를 들어 pets/dog.pngpets%2Fdog.png로 URL 인코딩됩니다.

XML API

  1. OAuth 2.0 Playground에서 승인 액세스 토큰을 가져옵니다. 자체 OAuth 사용자 인증 정보를 사용하도록 Playground를 구성합니다. 자세한 내용은 API 인증을 참조하세요.
  2. cURL을 사용하여 GET 객체 요청으로 XML API를 호출합니다.

    curl -X GET \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      -o "SAVE_TO_LOCATION" \
      "https://storage.googleapis.com/BUCKET_NAME/OBJECT_NAME"

    각 항목의 의미는 다음과 같습니다.

    • OAUTH2_TOKEN은 1단계에서 생성한 액세스 토큰입니다.
    • SAVE_TO_LOCATION은 객체를 저장할 위치의 경로입니다. 예를 들면 Desktop/dog.png입니다.
    • BUCKET_NAME은 다운로드할 객체가 포함된 버킷의 이름입니다. 예: my-bucket
    • OBJECT_NAME은 다운로드할 객체의 URL 인코딩 이름입니다. 예를 들어 pets/dog.pngpets%2Fdog.png로 URL 인코딩됩니다.

버킷이나 하위 디렉터리에 있는 모든 객체를 보다 효율적으로 다운로드하려면 gcloud storage cp 명령어 또는 클라이언트 라이브러리를 사용합니다.

객체 일부 다운로드

다운로드가 중단되면 나머지 객체 부분만 요청하여 중단한 부분부터 계속할 수 있습니다. 다음 안내를 수행하여 객체 일부를 다운로드합니다.

콘솔

Google Cloud Console에서는 객체 일부를 다운로드할 수 없습니다. 대신 gcloud CLI를 사용하세요.

명령줄

Google Cloud CLI는 스트리밍 전송을 수행하는 경우를 제외하고 중단된 다운로드를 자동으로 계속하려고 합니다. 다운로드가 중단되면 부분적으로 다운로드된 임시 파일이 대상 계층 구조에 표시됩니다. 같은 cp 명령어를 실행하여 중단된 지점부터 다운로드를 계속합니다.

다운로드가 완료되면 임시 파일이 삭제되고 다운로드한 콘텐츠로 교체됩니다. 임시 파일은 구성 가능한 위치(기본적으로 .config/gcloud/surface_data/storage/tracker_files의 사용자 홈 디렉터리)에 저장됩니다. gcloud config get storage/tracker_files_directory를 실행하여 임시 파일이 저장되는 위치를 변경하거나 볼 수 있습니다.

클라이언트 라이브러리

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, std::int64_t start, std::int64_t end) {
  gcs::ObjectReadStream stream =
      client.ReadObject(bucket_name, object_name, gcs::ReadRange(start, end));

  int count = 0;
  std::string line;
  while (std::getline(stream, line, '\n')) {
    std::cout << line << "\n";
    ++count;
  }
  if (stream.bad()) throw google::cloud::Status(stream.status());

  std::cout << "The requested range has " << count << " lines\n";
}

C#

자세한 내용은 Cloud Storage C# API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


using Google.Apis.Storage.v1;
using Google.Cloud.Storage.V1;
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

public class DownloadByteRangeAsyncSample
{
    public async Task DownloadByteRangeAsync(
        string bucketName = "your-unique-bucket-name",
        string objectName = "my-file-name",
        long firstByte = 0,
        long lastByte = 20,
        string localPath = "my-local-path/my-file-name")
    {
        var storageClient = StorageClient.Create();

        // Create an HTTP request for the media, for a limited byte range.
        StorageService storage = storageClient.Service;
        var uri = new Uri($"{storage.BaseUri}b/{bucketName}/o/{objectName}?alt=media");

        var request = new HttpRequestMessage { RequestUri = uri };
        request.Headers.Range = new RangeHeaderValue(firstByte, lastByte);

        using var outputFile = File.OpenWrite(localPath);
        // Use the HttpClient in the storage object because it supplies
        // all the authentication headers we need.
        var response = await storage.HttpClient.SendAsync(request);
        await response.Content.CopyToAsync(outputFile, null);
        Console.WriteLine($"Downloaded {objectName} to {localPath}.");
    }
}

Go

자세한 내용은 Cloud Storage Go API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

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

// downloadByteRange downloads a specific byte range of an object to a file.
func downloadByteRange(w io.Writer, bucket, object string, startByte int64, endByte int64, destFileName string) error {
	// bucket := "bucket-name"
	// object := "object-name"
	// startByte := 0
	// endByte := 20
	// destFileName := "file.txt"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

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

	f, err := os.Create(destFileName)
	if err != nil {
		return fmt.Errorf("os.Create: %w", err)
	}

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

	if _, err := io.Copy(f, rc); err != nil {
		return fmt.Errorf("io.Copy: %w", err)
	}

	if err = f.Close(); err != nil {
		return fmt.Errorf("f.Close: %w", err)
	}

	fmt.Fprintf(w, "Bytes %v to %v of blob %v downloaded to local file %v\n", startByte, startByte+length, object, destFileName)

	return nil

}

Java

자세한 내용은 Cloud Storage Java API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


import com.google.cloud.ReadChannel;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import com.google.common.io.ByteStreams;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class DownloadByteRange {

  public static void downloadByteRange(
      String projectId,
      String bucketName,
      String blobName,
      long startByte,
      long endBytes,
      String destFileName)
      throws IOException {
    // The ID of your GCP project
    // String projectId = "your-project-id";

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

    // The name of the blob/file that you wish to modify permissions on
    // String blobName = "your-blob-name";

    // The starting byte at which to begin the download
    // long startByte = 0;

    // The ending byte at which to end the download
    // long endByte = 20;

    // The path to which the file should be downloaded
    // String destFileName = '/local/path/to/file.txt';

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    BlobId blobId = BlobId.of(bucketName, blobName);
    try (ReadChannel from = storage.reader(blobId);
        FileChannel to = FileChannel.open(Paths.get(destFileName), StandardOpenOption.WRITE)) {
      from.seek(startByte);
      from.limit(endBytes);

      ByteStreams.copy(from, to);

      System.out.printf(
          "%s downloaded to %s from byte %d to byte %d",
          blobId.toGsUtilUri(), destFileName, startByte, endBytes);
    }
  }
}

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';

// The starting byte at which to begin the download
// const startByte = 0;

// The ending byte at which to end the download
// const endByte = 20;

// The path to which the file should be downloaded
// const destFileName = '/local/path/to/file.txt';

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

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

async function downloadByteRange() {
  const options = {
    destination: destFileName,
    start: startByte,
    end: endByte,
  };

  // Downloads the file from the starting byte to the ending byte specified in options
  await storage.bucket(bucketName).file(fileName).download(options);

  console.log(
    `gs://${bucketName}/${fileName} downloaded to ${destFileName} from byte ${startByte} to byte ${endByte}.`
  );
}

downloadByteRange();

PHP

자세한 내용은 Cloud Storage PHP API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

use Google\Cloud\Storage\StorageClient;

/**
 * Download a byte range from Cloud Storage and save it as a local file.
 *
 * @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')
 * @param int $startByte The starting byte at which to begin the download.
 *        (e.g. 1)
 * @param int $endByte The ending byte at which to end the download. (e.g. 5)
 * @param string $destination The local destination to save the object.
 *        (e.g. '/path/to/your/file')
 */
function download_byte_range(
    string $bucketName,
    string $objectName,
    int $startByte,
    int $endByte,
    string $destination
): void {
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $object->downloadToFile($destination, [
        'restOptions' => [
            'headers' => [
                'Range' => "bytes=$startByte-$endByte",
            ],
        ],
    ]);
    printf(
        'Downloaded gs://%s/%s to %s' . PHP_EOL,
        $bucketName,
        $objectName,
        basename($destination)
    );
}

Python

자세한 내용은 Cloud Storage Python API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

from google.cloud import storage


def download_byte_range(
    bucket_name, source_blob_name, start_byte, end_byte, destination_file_name
):
    """Downloads a blob from the bucket."""
    # The ID of your GCS bucket
    # bucket_name = "your-bucket-name"

    # The ID of your GCS object
    # source_blob_name = "storage-object-name"

    # The starting byte at which to begin the download
    # start_byte = 0

    # The ending byte at which to end the download
    # end_byte = 20

    # The path to which the file should be downloaded
    # destination_file_name = "local/path/to/file"

    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(source_blob_name)
    blob.download_to_filename(destination_file_name, start=start_byte, end=end_byte)

    print(
        "Downloaded bytes {} to {} of object {} from bucket {} to local file {}.".format(
            start_byte, end_byte, source_blob_name, bucket_name, destination_file_name
        )
    )

Ruby

자세한 내용은 Cloud Storage Ruby API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

# The ID of your GCS bucket
# bucket_name = "your-unique-bucket-name"

# file_name = "Name of a file in the Storage bucket"

# The starting byte at which to begin the download
# start_byte = 0

# The ending byte at which to end the download
# end_byte = 20

# The path to which the file should be downloaded
# local_file_path = "/local/path/to/file.txt"

require "google/cloud/storage"

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

file.download local_file_path, range: start_byte..end_byte

puts "Downloaded bytes #{start_byte} to #{end_byte} of object #{file_name} from bucket #{bucket_name}" \
     + " to local file #{local_file_path}."

REST API

JSON API

요청의 Range 헤더를 사용하여 객체 일부를 다운로드합니다.

  1. OAuth 2.0 Playground에서 승인 액세스 토큰을 가져옵니다. 자체 OAuth 사용자 인증 정보를 사용하도록 Playground를 구성합니다. 자세한 내용은 API 인증을 참조하세요.
  2. cURL을 사용하여 GET 객체 요청으로 JSON API를 호출합니다.

    curl -X GET \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      -H "Range: bytes=FIRST_BYTE-LAST_BYTE" \
      -o "SAVE_TO_LOCATION" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/o/OBJECT_NAME?alt=media"

    각 항목의 의미는 다음과 같습니다.

    • OAUTH2_TOKEN은 1단계에서 생성한 액세스 토큰입니다.
    • FIRST_BYTE는 다운로드할 바이트 범위의 첫 번째 바이트입니다. 예를 들면 1000입니다.
    • LAST_BYTE는 다운로드할 바이트 범위의 마지막 바이트입니다. 예를 들면 1999입니다.
    • SAVE_TO_LOCATION은 객체를 저장할 위치의 경로입니다. 예를 들면 Desktop/dog.png입니다.
    • BUCKET_NAME은 다운로드할 객체가 포함된 버킷의 이름입니다. 예: my-bucket
    • OBJECT_NAME은 다운로드할 객체의 URL 인코딩 이름입니다. 예를 들어 pets/dog.pngpets%2Fdog.png로 URL 인코딩됩니다.

XML API

요청의 Range 헤더를 사용하여 객체 일부를 다운로드합니다.

  1. OAuth 2.0 Playground에서 승인 액세스 토큰을 가져옵니다. 자체 OAuth 사용자 인증 정보를 사용하도록 Playground를 구성합니다. 자세한 내용은 API 인증을 참조하세요.
  2. cURL을 사용하여 GET 객체 요청으로 XML API를 호출합니다.

    curl -X GET \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      -H "Range: bytes=FIRST_BYTE-LAST_BYTE" \
      -o "SAVE_TO_LOCATION" \
      "https://storage.googleapis.com/BUCKET_NAME/OBJECT_NAME"

    각 항목의 의미는 다음과 같습니다.

    • OAUTH2_TOKEN은 1단계에서 생성한 액세스 토큰입니다.
    • FIRST_BYTE는 다운로드할 바이트 범위의 첫 번째 바이트입니다. 예를 들면 1000입니다.
    • LAST_BYTE는 다운로드할 바이트 범위의 마지막 바이트입니다. 예를 들면 1999입니다.
    • SAVE_TO_LOCATION은 객체를 저장할 위치의 경로입니다. 예를 들면 $HOME/Desktop/dog.png입니다.
    • BUCKET_NAME은 다운로드할 객체가 포함된 버킷의 이름입니다. 예: my-bucket
    • OBJECT_NAME은 다운로드할 객체의 URL 인코딩 이름입니다. 예를 들어 pets/dog.pngpets%2Fdog.png로 URL 인코딩됩니다.

다음 단계

직접 사용해 보기

Google Cloud를 처음 사용하는 경우 계정을 만들어 실제 시나리오에서 Cloud Storage의 성능을 평가할 수 있습니다. 신규 고객에게는 워크로드를 실행, 테스트, 배포하는 데 사용할 수 있는 $300의 무료 크레딧이 제공됩니다.

Cloud Storage 무료로 사용해 보기