使用要求者付費功能

本頁面說明要求者付費功能的設定方式,並舉例說明如何在已啟用要求者付費功能的值區上提出要求。如需此功能的相關說明,請參閱要求者付費一文。

設定要求者付費

以下章節說明如何開啟或關閉要求者付費,以及如何確認值區是否已啟用要求者付費。

必備條件

  1. 您應該具備 storage.buckets.get 權限,該權限可讓您取得值區的要求者付費狀態,也是透過 Google Cloud Platform Console 或 gsutil 啟用及停用要求者付費的必要權限。

  2. 當您啟用或停用要求者付費時,您必須擁有 storage.buckets.update 權限。

  3. 當您停用要求者付費時,您必須在要求中包含計費專案,或擁有 resourcemanager.projects.createBillingAssignment 權限。詳情請參閱要求者付費的使用及存取需求一節。

您可以透過角色將權限授予使用者。例如,擁有 roles/storage.admin 的使用者具備上述所有的 storage.buckets 權限。您可以將角色新增至包含值區的專案

啟用要求者付費

如何在值區上啟用要求者付費:

主控台

  1. 在 Google Cloud Platform Console 中開啟 Cloud Storage 瀏覽器。
    開啟 Cloud Storage 瀏覽器
  2. 在值區清單中找到要啟用的值區,然後點選「Requester pays」(要求者付費) 欄旁邊的 [Off] (關閉) 按鈕。

  3. 在顯示的視窗中按一下 [Enable] (啟用)。

啟用功能後,值區的「Requester pays」 (要求者付費) 欄中隨即顯示綠色泡泡和「On」(開啟)。

gsutil

使用 gsutil requesterpays set on 指令:

gsutil requesterpays set on gs://[BUCKET_NAME]

其中 [BUCKET_NAME] 是相關值區的名稱。例如:my-bucket

程式碼範例

C++

詳情請參閱 Cloud Storage C++ API 參考說明文件

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string bucket_name) {
  StatusOr<gcs::BucketMetadata> bucket_metadata = client.PatchBucket(
      bucket_name,
      gcs::BucketMetadataPatchBuilder().SetBilling(gcs::BucketBilling{true}));

  if (!bucket_metadata) {
    throw std::runtime_error(bucket_metadata.status().message());
  }

  std::cout << "Billing configuration for bucket " << bucket_metadata->name()
            << " is updated. The bucket now";
  if (!bucket_metadata->has_billing()) {
    std::cout << " has no billing configuration.\n";
  } else if (bucket_metadata->billing().requester_pays) {
    std::cout << " is configured to charge the caller for requests\n";
  } else {
    std::cout << " is configured to charge the project that owns the bucket"
              << " for requests.\n";
  }
}

C#

詳情請參閱 Cloud Storage C# API 參考說明文件

void EnableRequesterPays(string bucketName)
{
    var storage = StorageClient.Create();
    var bucket = storage.GetBucket(bucketName, new GetBucketOptions()
    {
        UserProject = s_projectId
    });
    bucket.Billing = bucket.Billing ?? new Bucket.BillingData();
    bucket.Billing.RequesterPays = true;
    bucket = storage.UpdateBucket(bucket, new UpdateBucketOptions()
    {
        // Use IfMetagenerationMatch to avoid race conditions.
        IfMetagenerationMatch = bucket.Metageneration,
        UserProject = s_projectId
    });
}

Go

詳情請參閱 Cloud Storage Go API 參考說明文件

bucket := c.Bucket(bucketName)
bucketAttrsToUpdate := storage.BucketAttrsToUpdate{
	RequesterPays: true,
}
if _, err := bucket.Update(ctx, bucketAttrsToUpdate); err != nil {
	return err
}

Java

詳情請參閱 Cloud Storage Java API 參考說明文件

// Instantiate a Google Cloud Storage client
Storage storage = StorageOptions.getDefaultInstance().getService();

// The name of the existing bucket to enable requester-paying for, e.g. "my-bucket"
// String bucketName = "my-bucket"
BucketInfo bucketInfo = BucketInfo.newBuilder(bucketName).setRequesterPays(true).build();

// Update the bucket, throws StorageException on failure
Bucket bucket = storage.update(bucketInfo);

System.out.println("Requester pay status for " + bucketName + ": " + bucket.requesterPays());

Node.js

詳情請參閱 Cloud Storage Node.js API 參考說明文件

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

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

/**
 * TODO(developer): Uncomment the following line before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';

// Enables requester-pays requests
await storage.bucket(bucketName).enableRequesterPays();

console.log(
  `Requester-pays requests have been enabled for bucket ${bucketName}.`
);

PHP

詳情請參閱 Cloud Storage PHP API 參考說明文件

use Google\Cloud\Storage\StorageClient;

/**
 * Enable a bucket's requesterpays metadata.
 *
 * @param string $projectId Your Google Cloud project ID.
 * @param string $bucketName Name of your Google Cloud Storage bucket.
 *
 * @return void
 */
function enable_requester_pays($projectId, $bucketName)
{
    $storage = new StorageClient([
        'projectId' => $projectId
    ]);
    $bucket = $storage->bucket($bucketName);
    $bucket->update([
        'billing' => [
            'requesterPays' => true
        ]
    ]);
    printf('Requester pays has been enabled for %s' . PHP_EOL, $bucketName);
}

Python

詳情請參閱 Cloud Storage Python API 參考說明文件

def enable_requester_pays(bucket_name):
    """Enable a bucket's requesterpays metadata"""
    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucket_name)
    bucket.requester_pays = True
    bucket.patch()
    print('Requester Pays has been enabled for {}'.format(bucket_name))

Ruby

詳情請參閱 Cloud Storage Ruby API 參考說明文件

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Name of your Google Cloud Storage bucket"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new project_id: project_id
bucket  = storage.bucket bucket_name

bucket.requester_pays = true

puts "Requester pays has been enabled for #{bucket_name}"

REST API

JSON API

  1. OAuth 2.0 Playground 取得授權存取憑證。將 Playground 設為使用自己的 OAuth 憑證。
  2. 建立包含下列資訊的 .json 檔案:

    {
      "billing": {
        "requesterPays": true
      }
    }
  3. 使用 cURL 來透過 PATCH 值區要求呼叫 JSON API

    curl -X PATCH --data-binary @[JSON_FILE_NAME].json \
      -H "Authorization: Bearer [OAUTH2_TOKEN]" \
      -H "Content-Type: application/json" \
      "https://www.googleapis.com/storage/v1/b/[BUCKET_NAME]?fields=billing"

    其中:

    • [JSON_FILE_NAME] 是您在步驟 2 建立的檔案名稱。
    • [OAUTH2_TOKEN] 是您在步驟 1 產生的存取憑證的名稱。
    • [BUCKET_NAME] 是相關值區的名稱。例如:my-bucket

XML API

  1. OAuth 2.0 Playground 取得授權存取憑證。將 Playground 設為使用自己的 OAuth 憑證。
  2. 建立包含下列資訊的 .xml 檔案:

    <BillingConfiguration>
      <RequesterPays>Enabled</RequesterPays>
    </BillingConfiguration>
  3. 使用 cURL 透過 PUT 值區要求和 requesterpays 查詢字串參數來呼叫 XML API

    curl -X PUT --data-binary @[XML_FILE_NAME].xml \
      -H "Authorization: Bearer [OAUTH2_TOKEN]" \
      "https://storage.googleapis.com/[BUCKET_NAME]?billing"

    其中:

    • [XML_FILE_NAME] 是您在步驟 2 建立的檔案名稱。
    • [OAUTH2_TOKEN] 是您在步驟 1 產生的存取憑證的名稱。
    • [BUCKET_NAME] 是相關值區的名稱。例如:my-bucket

停用要求者付費

如何在值區上停用要求者付費:

主控台

  1. 在 Google Cloud Platform Console 中開啟 Cloud Storage 瀏覽器。
    開啟 Cloud Storage 瀏覽器
  2. 在值區清單中找到要停用的值區,然後點選「Requester pays」(要求者付費) 欄旁邊的 [On] (開啟) 按鈕。

  3. 在顯示的視窗中按一下 [Disable] (停用)。

停用功能後,「Requester pays」(要求者付費) 欄中隨即顯示灰色泡泡和「Off」(關閉)。

gsutil

使用 gsutil requesterpays set off 指令:

gsutil requesterpays set off gs://[BUCKET_NAME]

其中 [BUCKET_NAME] 是相關值區的名稱。例如:my-bucket

程式碼範例

C++

詳情請參閱 Cloud Storage C++ API 參考說明文件

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string bucket_name, std::string project_id) {
  StatusOr<gcs::BucketMetadata> bucket_metadata = client.PatchBucket(
      bucket_name,
      gcs::BucketMetadataPatchBuilder().SetBilling(gcs::BucketBilling{false}),
      gcs::UserProject(project_id));

  if (!bucket_metadata) {
    throw std::runtime_error(bucket_metadata.status().message());
  }

  std::cout << "Billing configuration for bucket " << bucket_name
            << " is updated. The bucket now";
  if (!bucket_metadata->has_billing()) {
    std::cout << " has no billing configuration.\n";
  } else if (bucket_metadata->billing().requester_pays) {
    std::cout << " is configured to charge the caller for requests\n";
  } else {
    std::cout << " is configured to charge the project that owns the bucket"
              << " for requests.\n";
  }
}

C#

詳情請參閱 Cloud Storage C# API 參考說明文件

void DisableRequesterPays(string bucketName)
{
    var storage = StorageClient.Create();
    var bucket = storage.GetBucket(bucketName, new GetBucketOptions()
    {
        UserProject = s_projectId
    });
    bucket.Billing = bucket.Billing ?? new Bucket.BillingData();
    bucket.Billing.RequesterPays = false;
    bucket = storage.UpdateBucket(bucket, new UpdateBucketOptions()
    {
        // Use IfMetagenerationMatch to avoid race conditions.
        IfMetagenerationMatch = bucket.Metageneration,
        UserProject = s_projectId
    });
}

Go

詳情請參閱 Cloud Storage Go API 參考說明文件

bucket := c.Bucket(bucketName)
bucketAttrsToUpdate := storage.BucketAttrsToUpdate{
	RequesterPays: false,
}
if _, err := bucket.Update(ctx, bucketAttrsToUpdate); err != nil {
	return err
}

Java

詳情請參閱 Cloud Storage Java API 參考說明文件

// Instantiate a Google Cloud Storage client
Storage storage = StorageOptions.getDefaultInstance().getService();

// The name of the bucket to disable requester-paying for, e.g. "my-bucket"
// String bucketName = "my-bucket"
BucketInfo bucketInfo = BucketInfo.newBuilder(bucketName).setRequesterPays(false).build();

// Update the bucket, throws StorageException on failure
Bucket bucket = storage.update(bucketInfo);

System.out.println("Requester pays status for " + bucketName + ": " + bucket.requesterPays());

Node.js

詳情請參閱 Cloud Storage Node.js API 參考說明文件

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

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

/**
 * TODO(developer): Uncomment the following line before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';

// Disables requester-pays requests
await storage.bucket(bucketName).disableRequesterPays();

console.log(
  `Requester-pays requests have been disabled for bucket ${bucketName}.`
);

PHP

詳情請參閱 Cloud Storage PHP API 參考說明文件

use Google\Cloud\Storage\StorageClient;

/**
 * Disable a bucket's requesterpays metadata.
 *
 * @param string $projectId Your Google Cloud project ID.
 * @param string $bucketName Name of your Google Cloud Storage bucket.
 *
 * @return void
 */
function disable_requester_pays($projectId, $bucketName)
{
    $storage = new StorageClient([
        'projectId' => $projectId
    ]);
    $bucket = $storage->bucket($bucketName);
    $bucket->update([
        'billing' => [
            'requesterPays' => false
        ]
    ]);
    printf('Requester pays has been disabled for %s' . PHP_EOL, $bucketName);
}

Python

詳情請參閱 Cloud Storage Python API 參考說明文件

def disable_requester_pays(bucket_name):
    """Disable a bucket's requesterpays metadata"""
    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucket_name)
    bucket.requester_pays = False
    bucket.patch()
    print('Requester Pays has been disabled for {}'.format(bucket_name))

Ruby

詳情請參閱 Cloud Storage Ruby API 參考說明文件

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Name of your Google Cloud Storage bucket"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new project_id: project_id
bucket  = storage.bucket bucket_name

bucket.requester_pays = false

puts "Requester pays has been disabled for #{bucket_name}"

REST API

JSON API

  1. OAuth 2.0 Playground 取得授權存取憑證。將 Playground 設為使用自己的 OAuth 憑證。
  2. 建立包含下列資訊的 .json 檔案:

    {
      "billing": {
        "requesterPays": false
      }
    }
  3. 使用 cURL 來透過 PATCH 值區要求呼叫 JSON API

    curl -X PATCH --data-binary @[JSON_FILE_NAME].json \
      -H "Authorization: Bearer [OAUTH2_TOKEN]" \
      -H "Content-Type: application/json" \
      "https://www.googleapis.com/storage/v1/b/[BUCKET_NAME]?fields=billing"

    其中:

    • [JSON_FILE_NAME] 是您在步驟 2 建立的檔案名稱。
    • [OAUTH2_TOKEN] 是您在步驟 1 產生的存取憑證的名稱。
    • [BUCKET_NAME] 是相關值區的名稱。例如:my-bucket

XML API

  1. OAuth 2.0 Playground 取得授權存取憑證。將 Playground 設為使用自己的 OAuth 憑證。
  2. 建立包含下列資訊的 .xml 檔案:

    <BillingConfiguration>
      <RequesterPays>Disabled</RequesterPays>
    </BillingConfiguration>
  3. 使用 cURL 透過 PUT 值區要求和 requesterpays 查詢字串參數來呼叫 XML API

    curl -X PUT --data-binary @[XML_FILE_NAME].xml \
      -H "Authorization: Bearer [OAUTH2_TOKEN]" \
      "https://storage.googleapis.com/[BUCKET_NAME]?billing"

    其中:

    • [XML_FILE_NAME] 是您在步驟 2 建立的檔案名稱。
    • [OAUTH2_TOKEN] 是您在步驟 1 產生的存取憑證的名稱。
    • [BUCKET_NAME] 是相關值區的名稱。例如:my-bucket

檢查是否已啟用要求者付費

如何檢查值區是否已啟用要求者付費:

主控台

  1. 在 Google Cloud Platform Console 中開啟 Cloud Storage 瀏覽器。
    開啟 Cloud Storage 瀏覽器
  2. 在值區清單中,每個值區的要求者付費狀態都會顯示在「Requester Pays」(要求者付費) 欄中。

如果已啟用,狀態為綠色並顯示「On」(開啟) 字樣。

gsutil

使用 gsutil requesterpays get 指令:

gsutil requesterpays get gs://[BUCKET_NAME]

其中 [BUCKET_NAME] 是相關值區的名稱。例如:my-bucket

如果要求者付費已啟用,回應看起來會像下列範例:

gs://[BUCKET_NAME]: Enabled

程式碼範例

C++

詳情請參閱 Cloud Storage C++ API 參考說明文件

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string bucket_name) {
  StatusOr<gcs::BucketMetadata> bucket_metadata =
      client.GetBucketMetadata(bucket_name);

  if (!bucket_metadata) {
    throw std::runtime_error(bucket_metadata.status().message());
  }

  if (!bucket_metadata->has_billing()) {
    std::cout
        << "The bucket " << bucket_metadata->name() << " does not have a"
        << " billing configuration. The default applies, i.e., the project"
        << " that owns the bucket pays for the requests.\n";
    return;
  }

  if (bucket_metadata->billing().requester_pays) {
    std::cout
        << "The bucket " << bucket_metadata->name()
        << " is configured to charge the calling project for the requests.\n";
  } else {
    std::cout << "The bucket " << bucket_metadata->name()
              << " is configured to charge the project that owns the bucket "
                 "for the requests.\n";
  }
}

C#

詳情請參閱 Cloud Storage C# API 參考說明文件

bool GetRequesterPays(string bucketName)
{
    var storage = StorageClient.Create();
    var bucket = storage.GetBucket(bucketName, new GetBucketOptions()
    {
        UserProject = s_projectId
    });
    bool? requesterPaysOrNull = bucket.Billing?.RequesterPays;
    bool requesterPays =
        requesterPaysOrNull.HasValue ? requesterPaysOrNull.Value : false;
    Console.WriteLine("RequesterPays: {0}", requesterPays);
    return requesterPays;
}

Go

詳情請參閱 Cloud Storage Go API 參考說明文件

attrs, err := c.Bucket(bucketName).Attrs(ctx)
if err != nil {
	return err
}
log.Printf("Is requester pays enabled? %v\n", attrs.RequesterPays)

Java

詳情請參閱 Cloud Storage Java API 參考說明文件

// Instantiate a Google Cloud Storage client
Storage storage = StorageOptions.getDefaultInstance().getService();

// The name of the bucket to retrieve requester-pays status, eg. "my-bucket"
// String bucketName = "my-bucket"
// Retrieve the bucket, throws StorageException on failure
Bucket bucket = storage.get(bucketName, Storage.BucketGetOption.fields(BucketField.BILLING));

System.out.println("Requester pays status : " + bucket.requesterPays());

Node.js

詳情請參閱 Cloud Storage Node.js API 參考說明文件

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

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

/**
 * TODO(developer): Uncomment the following line before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';

// Gets the requester-pays status of a bucket
const [metadata] = await storage.bucket(bucketName).getMetadata();

let status;
if (metadata && metadata.billing && metadata.billing.requesterPays) {
  status = `enabled`;
} else {
  status = `disabled`;
}
console.log(
  `Requester-pays requests are ${status} for bucket ${bucketName}.`
);

PHP

詳情請參閱 Cloud Storage PHP API 參考說明文件

use Google\Cloud\Storage\StorageClient;

/**
 * Get a bucket's requesterpays metadata.
 *
 * @param string $projectId Your Google Cloud project ID.
 * @param string $bucketName Name of your Google Cloud Storage bucket.
 *
 * @return void
 */
function get_requester_pays_status($projectId, $bucketName)
{
    $storage = new StorageClient([
        'projectId' => $projectId
    ]);
    $bucket = $storage->bucket($bucketName);
    $bucketInformation = $bucket->info();
    $requesterPaysStatus = $bucketInformation['billing']['requesterPays'];
    if ($requesterPaysStatus) {
        printf('Requester Pays is enabled for %s' . PHP_EOL, $bucketName);
    } else {
        printf('Requester Pays is disabled for %s' . PHP_EOL, $bucketName);
    }
}

Python

詳情請參閱 Cloud Storage Python API 參考說明文件

def get_requester_pays_status(bucket_name):
    """Get a bucket's requester pays metadata"""
    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucket_name)
    requester_pays_status = bucket.requester_pays
    if requester_pays_status:
        print('Requester Pays is enabled for {}'.format(bucket_name))
    else:
        print('Requester Pays is disabled for {}'.format(bucket_name))

Ruby

詳情請參閱 Cloud Storage Ruby API 參考說明文件

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Name of your Google Cloud Storage bucket"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new project_id: project_id
bucket  = storage.bucket bucket_name

if bucket.requester_pays
  puts "Requester Pays is enabled for #{bucket_name}"
else
  puts "Requester Pays is disabled for #{bucket_name}"
end

REST API

JSON API

  1. OAuth 2.0 Playground 取得授權存取憑證。將 Playground 設為使用自己的 OAuth 憑證。
  2. 使用 cURL 來透過 GET 值區要求呼叫 JSON API

    curl -X GET \
      -H "Authorization: Bearer [OAUTH2_TOKEN]" \
      "https://www.googleapis.com/storage/v1/b/[BUCKET_NAME]?fields=billing"

    其中:

    • [OAUTH2_TOKEN] 是您在步驟 1 產生的存取憑證的名稱。
    • [BUCKET_NAME] 是相關值區的名稱。例如:my-bucket

XML API

  1. OAuth 2.0 Playground 取得授權存取憑證。將 Playground 設為使用自己的 OAuth 憑證。
  2. 使用 cURL 透過 GET 值區要求和 billing 查詢字串參數來呼叫 XML API

    curl -X GET \
      -H "Authorization: Bearer [OAUTH2_TOKEN]" \
      "https://storage.googleapis.com/[BUCKET_NAME]?billing"

    其中:

    • [OAUTH2_TOKEN] 是您在步驟 1 產生的存取憑證的名稱。
    • [BUCKET_NAME] 是相關值區的名稱。例如:my-bucket

存取要求者付費值區

以下範例說明如何納入計費專案,以便您下載儲存在要求者付費值區中的物件。請利用類似的程序在要求者付費值區或其中的物件上執行其他要求。如需必要條件資訊,請參閱要求者付費存取需求條件

主控台

  1. 在 Google Cloud Platform Console 中開啟 Cloud Storage 瀏覽器。
    開啟 Cloud Storage 瀏覽器
  2. 在值區清單中,點選含有您要下載物件的值區名稱。

  3. 在隨即顯示的視窗中,使用下拉式選單選取計費的專案。

  4. 勾選核取方塊以確認您已獲授權可將所選的專案用於計費用途。

  5. 按一下 [Save] (儲存)

  6. 按照平常方式下載物件

gsutil

在要求中使用 -u 標記:

gsutil -u [PROJECT_ID] cp gs://[BUCKET_NAME]/[OBJECT_NAME] [OBJECT_DESTINATION]

其中:

  • [PROJECT_ID] 是要計費的專案 ID。例如:my-project
  • [BUCKET_NAME] 是相關值區的名稱。例如:my-bucket
  • [OBJECT_NAME] 是您要下載的物件名稱。例如:pets/dog.png
  • [OBJECT_DESTINATION] 是您要儲存物件的位置。例如:Desktop/dog.png

程式碼範例

C++

詳情請參閱 Cloud Storage C++ API 參考說明文件

namespace gcs = google::cloud::storage;
[](gcs::Client client, std::string bucket_name, std::string object_name,
   std::string billed_project) {
  gcs::ObjectReadStream stream = client.ReadObject(
      bucket_name, object_name, gcs::UserProject(billed_project));

  std::string line;
  while (std::getline(stream, line, '\n')) {
    std::cout << line << "\n";
  }
}

C#

詳情請參閱 Cloud Storage C# API 參考說明文件

private void DownloadObjectRequesterPays(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,
            new DownloadObjectOptions()
            {
                UserProject = s_projectId
            });
    }
    Console.WriteLine(
        $"downloaded {objectName} to {localPath} paid by {s_projectId}.");
}

Go

詳情請參閱 Cloud Storage Go API 參考說明文件

bucket := client.Bucket(bucketName).UserProject(billingProjectID)
src := bucket.Object(object)

f, err := os.OpenFile(localpath, os.O_RDWR|os.O_CREATE, 0755)
if err != nil {
	return err
}
rc, err := src.NewReader(ctx)
if err != nil {
	return err
}
if _, err := io.Copy(f, rc); err != nil {
	return err
}
if err := rc.Close(); err != nil {
	return err
}
fmt.Printf("Downloaded using %v as billing project.\n", billingProjectID)

Java

詳情請參閱 Cloud Storage Java API 參考說明文件

// The project ID to bill
// String projectId = "my-billable-project-id";

// The name of the bucket to access
// String bucketName = "my-bucket";

// The name of the remote file to download
// String srcFilename = "file.txt";

// The path to which the file should be downloaded
// Path destFilePath = Paths.get("/local/path/to/file.txt");

// Instantiate a Google Cloud Storage client
Storage storage = StorageOptions.getDefaultInstance().getService();

// Get specific file from specified bucket
Blob blob = storage.get(BlobId.of(bucketName, srcFilename));

// Download file to specified path
blob.downloadTo(destFilePath, Blob.BlobSourceOption.userProject(projectId));

Node.js

詳情請參閱 Cloud Storage Node.js API 參考說明文件

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

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

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const projectId = 'The project ID to bill from, e.g. some-project-id';
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const srcFilename = 'Name of file to download, e.g. file.txt';
// const destFilename = 'Local destination of file, e.g. ./local/path/to/file.txt';

const options = {
  // The path to which the file should be downloaded, e.g. "./file.txt"
  destination: destFilename,

  // The project to bill from, if requester-pays requests are enabled
  userProject: projectId,
};

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

console.log(
  `gs://${bucketName}/${srcFilename} downloaded to ${destFilename} using requester-pays requests.`
);

PHP

詳情請參閱 Cloud Storage PHP API 參考說明文件

use Google\Cloud\Storage\StorageClient;

/**
 * Download file using specified project as requester
 *
 * @param string $projectId Your Google Cloud billable project ID.
 * @param string $bucketName A Google Cloud Storage bucket name.
 * @param string $objectName Name of object in Google Cloud Storage to download locally.
 * @param string $destination Path to local file to save.
 *
 * @return void
 */
function download_file_requester_pays($projectId, $bucketName, $objectName, $destination)
{
    $storage = new StorageClient([
        'projectId' => $projectId
    ]);
    $userProject = true;
    $bucket = $storage->bucket($bucketName, $userProject);
    $object = $bucket->object($objectName);
    $object->downloadToFile($destination);
    printf('Downloaded gs://%s/%s to %s using requester-pays requests.' . PHP_EOL,
        $bucketName, $objectName, basename($destination));
}

Python

詳情請參閱 Cloud Storage Python API 參考說明文件

def download_file_requester_pays(
        bucket_name, project_id, source_blob_name, destination_file_name):
    """Download file using specified project as the requester"""
    storage_client = storage.Client()
    user_project = project_id
    bucket = storage_client.bucket(bucket_name, user_project)
    blob = bucket.blob(source_blob_name)
    blob.download_to_filename(destination_file_name)

    print('Blob {} downloaded to {} using a requester-pays request.'.format(
        source_blob_name,
        destination_file_name))

Ruby

詳情請參閱 Cloud Storage Ruby API 參考說明文件

# project_id  = "Your Google Cloud billable project ID"
# bucket_name = "A 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 project_id: project_id
bucket  = storage.bucket bucket_name, skip_lookup: true, user_project: true
file    = bucket.file file_name

file.download local_path

puts "Downloaded #{file.name} using billing project #{project_id}"

REST API

JSON API

  1. OAuth 2.0 Playground 取得授權存取憑證。將 Playground 設為使用自己的 OAuth 憑證。
  2. 在要求中加入設為計費專案 ID 的 userProject 查詢字串參數:

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

    其中:

    • [OAUTH2_TOKEN] 是您在步驟 1 中產生的存取憑證。
    • [SAVE_TO_LOCATION] 是您要儲存物件的位置。例如:Desktop/dog.png
    • [BUCKET_NAME] 是相關值區的名稱。例如:my-bucket
    • [OBJECT_NAME] 是您要下載的物件名稱。例如:pets/dog.png
    • [PROJECT_ID] 是要計費的專案 ID。例如:my-project

XML API

  1. OAuth 2.0 Playground 取得授權存取憑證。將 Playground 設為使用自己的 OAuth 憑證。
  2. 在要求中加入設為計費專案 ID 的 x-goog-user-project 標頭:

    curl -X GET \
      -H "Authorization: Bearer [OAUTH2_TOKEN]" \
      -H "x-goog-user-project: [PROJECT_ID]" \
      -o "[SAVE_TO_LOCATION]" \
      "https://storage.googleapis.com/[BUCKET_NAME]/[OBJECT_NAME]"

    其中:

    • [OAUTH2_TOKEN] 是您在步驟 1 中產生的存取憑證。
    • [PROJECT_ID] 是要計費的專案 ID。例如:my-project
    • [SAVE_TO_LOCATION] 是您要儲存物件的位置。例如:Desktop/dog.png
    • [BUCKET_NAME] 是相關值區的名稱。例如:my-bucket
    • [OBJECT_NAME] 是您要下載的物件名稱。例如:pets/dog.png
本頁內容對您是否有任何幫助?請提供意見:

傳送您對下列選項的寶貴意見...

這個網頁
Cloud Storage
需要協助嗎?請前往我們的支援網頁