下载对象

本页面介绍如何从 Cloud Storage 中的存储分区下载对象。如需查看对象的概览,请参阅关键术语

控制台

  1. 在 Google Cloud Console 中打开 Cloud Storage 浏览器。
    打开 Cloud Storage 浏览器
  2. 在存储分区列表中,找到包含要下载的对象的存储分区,并点击其名称。

    此时会打开“存储分区详情”页面,其中“对象”标签页已选中。

  3. 导航到可能位于文件夹中的对象。

  4. 点击与对象关联的更多操作菜单 ()。

  5. 选择下载

请参阅问题排查,了解如何获取有关 Cloud Storage 浏览器中失败操作的详细错误信息。

gsutil

使用 gsutil cp 命令:

gsutil cp gs://BUCKET_NAME/OBJECT_NAME SAVE_TO_LOCATION

其中:

  • BUCKET_NAME 是包含要下载的对象的存储分区名称,例如 my-bucket

  • OBJECT_NAME 是要下载的对象的名称,例如 pets/dog.png

  • SAVE_TO_LOCATION 是保存对象的本地路径,例如 Desktop/Images

如果成功,则响应类似如下示例:

Operation completed over 1 objects/58.8 KiB.

代码示例

C++

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

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

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

C#

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

private void DownloadObject(string bucketName, string objectName,
    string localPath = null)
{
    var storage = StorageClient.Create();
    localPath = localPath ?? Path.GetFileName(objectName);
    using (var outputFile = File.OpenWrite(localPath))
    {
        storage.DownloadObject(bucketName, objectName, outputFile);
    }
    Console.WriteLine($"downloaded {objectName} to {localPath}.");
}

Go

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

import (
	"context"
	"fmt"
	"io"
	"io/ioutil"
	"time"

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

// downloadFile downloads an object.
func downloadFile(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: %v", 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: %v", object, err)
	}
	defer rc.Close()

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

Java

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

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.Path;

public class DownloadObject {
  public static void downloadObject(
      String projectId, String bucketName, String objectName, Path 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
    // Path destFilePath = Paths.get("/local/path/to/file.txt");

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

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

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

Node.js

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

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const srcFilename = 'Remote file to download, e.g. file.txt';
// const destFilename = 'Local destination for file, e.g. ./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 = {
    // The path to which the file should be downloaded, e.g. "./file.txt"
    destination: destFilename,
  };

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

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

downloadFile().catch(console.error);

PHP

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

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 Google Cloud bucket.
 * @param string $objectName the name of your Google Cloud object.
 * @param string $destination the local destination to save the encrypted object.
 *
 * @return void
 */
function download_object($bucketName, $objectName, $destination)
{
    $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 参考文档

from google.cloud import storage

def download_blob(bucket_name, source_blob_name, destination_file_name):
    """Downloads a blob from the bucket."""
    # bucket_name = "your-bucket-name"
    # source_blob_name = "storage-object-name"
    # destination_file_name = "local/path/to/file"

    storage_client = storage.Client()

    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(source_blob_name)
    blob.download_to_filename(destination_file_name)

    print(
        "Blob {} downloaded to {}.".format(
            source_blob_name, destination_file_name
        )
    )

Ruby

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

# bucket_name = "Your Google Cloud Storage bucket name"
# file_name   = "Name of file in Google Cloud Storage to download locally"
# local_path  = "Destination path for downloaded file"

require "google/cloud/storage"

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

file.download local_path

puts "Downloaded #{file.name}"

REST API

JSON API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  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 是要下载的对象的名称,例如 pets/dog.png。如需了解如何对对象名称进行网址编码以使其具备路径安全性,请参阅对 URI 路径部分进行编码

XML API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 使用 cURL,通过 GET Object 请求调用 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 是要下载的对象的名称,例如 pets/dog.png

要轻松下载存储分区或子目录中的所有对象,请使用 gsutil cp 命令。

后续步骤