Cloud Storage Client Libraries

This page shows how to get started with the Cloud Client Libraries for the Google Cloud Storage API. Read more about the client libraries for Cloud APIs, including the older Google APIs Client Libraries, in Client Libraries Explained.

Installing the client library

C++

See the GitHub README for details about this client library's requirements and install dependencies.

C#

For more information, see Setting Up a C# Development Environment. If you are using Visual Studio 2017 or higher, open nuget package manager window and type the following:

Install-Package Google.Cloud.Storage.V1

If you are using .NET Core command-line interface tools to install your dependencies, run the following command:

dotnet add package Google.Cloud.Storage.V1

Go

go get -u cloud.google.com/go/storage

Java

For more information, see Setting Up a Java Development Environment. 如果您使用的是 Maven,请将以下代码添加到您的 pom.xml 文件中:
<dependency>
  <groupId>com.google.cloud</groupId>
  <artifactId>google-cloud-storage</artifactId>
  <version>1.75.0</version>
</dependency>
如果您使用的是 Gradle,请将以下代码添加到您的依赖项中:
compile 'com.google.cloud:google-cloud-storage:1.75.0'
如果您使用的是 SBT,请将以下代码添加到您的依赖项中:
libraryDependencies += "com.google.cloud" % "google-cloud-storage" % "1.75.0"

如果您使用的是 IntelliJ 或 Eclipse,请通过以下 IDE 插件将客户端库添加到您的项目中:

上述插件还提供其他功能,例如服务帐号密钥管理。如需了解详情,请参阅各个插件相应的文档。

Node.js

For more information, see Setting Up a Node.js Development Environment.
npm install --save @google-cloud/storage

PHP

composer require google/cloud-storage

Python

For more information, see Setting Up a Python Development Environment.
pip install --upgrade google-cloud-storage

Ruby

For more information, see Setting Up a Ruby Development Environment.
gem install google-cloud-storage

Setting up authentication

To run the client library, you must first set up authentication by creating a service account and setting an environment variable. Complete the following steps to set up authentication. For more information, see the GCP authentication documentation .

GCP Console

  1. 在 GCP Console 中,转到创建服务帐号密钥页面。

    转到“创建服务帐号密钥”页面
  2. 服务帐号列表中,选择新的服务帐号
  3. 服务帐号名称字段中,输入一个名称。
  4. 角色列表中,选择项目 > 所有者

    注意角色字段为您的服务帐号授予资源访问权限。稍后您可以使用 GCP Console 查看和更改此字段。如果您开发的是正式版应用,请指定比项目 > 所有者更为精细的权限。如需了解详情,请参阅为服务帐号授予角色
  5. 点击创建。包含密钥的 JSON 文件就会下载到计算机。

命令行

您可以使用本地机器上的 Cloud SDK 或在 Cloud Shell 中运行以下命令。

  1. 创建服务帐号。将 [NAME] 替换为服务帐号的名称。

    gcloud iam service-accounts create [NAME]
  2. 向服务帐号授予权限。将 [PROJECT_ID] 替换为您的项目 ID。

    gcloud projects add-iam-policy-binding [PROJECT_ID] --member "serviceAccount:[NAME]@[PROJECT_ID].iam.gserviceaccount.com" --role "roles/owner"
    注意角色字段为您的服务帐号授予资源访问权限。稍后您可以使用 GCP Console 查看和更改此字段。如果您开发的是正式版应用,请指定比项目 > 所有者更为精细的权限。如需了解详情,请参阅为服务帐号授予角色
  3. 生成密钥文件。将 [FILE_NAME] 替换为密钥文件的名称。

    gcloud iam service-accounts keys create [FILE_NAME].json --iam-account [NAME]@[PROJECT_ID].iam.gserviceaccount.com

通过设置环境变量 GOOGLE_APPLICATION_CREDENTIALS,向您的应用代码提供身份验证凭据。将 [PATH] 替换为包含服务帐号密钥的 JSON 文件的文件路径,将 [FILE_NAME] 替换为文件名。此变量仅适用于当前的 shell 会话,因此,如果您打开新的会话,请重新设置该变量。

Linux 或 macOS

export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

例如:

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/[FILE_NAME].json"

Windows

使用 PowerShell:

$env:GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

例如:

$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\[FILE_NAME].json"

使用命令提示符:

set GOOGLE_APPLICATION_CREDENTIALS=[PATH]

Using the client library

The following example shows how to use the client library.

C++

#include "google/cloud/storage/client.h"
#include <iostream>

int main(int argc, char* argv[]) {
  if (argc != 3) {
    std::cerr << "Missing project id and/or bucket name.\n";
    std::cerr << "Usage: storage_quickstart <bucket-name> <project-id>\n";
    return 1;
  }
  std::string bucket_name = argv[1];
  std::string project_id = argv[2];

  // Create aliases to make the code easier to read.
  namespace gcs = google::cloud::storage;

  // Create a client to communicate with Google Cloud Storage. This client
  // uses the default configuration for authentication and project id.
  google::cloud::StatusOr<gcs::Client> client =
      gcs::Client::CreateDefaultClient();
  if (!client) {
    std::cerr << "Failed to create Storage Client, status=" << client.status()
              << "\n";
    return 1;
  }

  google::cloud::StatusOr<gcs::BucketMetadata> bucket_metadata =
      client->CreateBucketForProject(bucket_name, project_id,
                                     gcs::BucketMetadata());

  if (!bucket_metadata) {
    std::cerr << "Error creating bucket " << bucket_name
              << ", status=" << bucket_metadata.status() << "\n";
    return 1;
  }

  std::cout << "Created bucket " << bucket_metadata->name() << "\n";

  return 0;
}

C#


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

namespace GoogleCloudSamples
{
    class StorageQuickstart
    {
        static void Main(string[] args)
        {
            // Your Google Cloud Platform project ID.
            string projectId = "YOUR-PROJECT-ID";


            // Instantiates a client.
            StorageClient storageClient = StorageClient.Create();

            // The name for the new bucket.
            string bucketName = projectId + "-test-bucket";
            try
            {
                // Creates the new bucket.
                storageClient.CreateBucket(projectId, bucketName);
                Console.WriteLine($"Bucket {bucketName} created.");
            }
            catch (Google.GoogleApiException e)
            when (e.Error.Code == 409)
            {
                // The bucket already exists.  That's fine.
                Console.WriteLine(e.Error.Message);
            }
        }
    }
}

Go


// Sample storage-quickstart creates a Google Cloud Storage bucket.
package main

import (
	"context"
	"fmt"
	"log"

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

func main() {
	ctx := context.Background()

	// Sets your Google Cloud Platform project ID.
	projectID := "YOUR_PROJECT_ID"

	// Creates a client.
	client, err := storage.NewClient(ctx)
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}

	// Sets the name for the new bucket.
	bucketName := "my-new-bucket"

	// Creates a Bucket instance.
	bucket := client.Bucket(bucketName)

	// Creates the new bucket.
	if err := bucket.Create(ctx, projectID, nil); err != nil {
		log.Fatalf("Failed to create bucket: %v", err)
	}

	fmt.Printf("Bucket %v created.\n", bucketName)
}

Java

// Imports the Google Cloud client library
import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class QuickstartSample {
  public static void main(String... args) throws Exception {
    // Instantiates a client
    Storage storage = StorageOptions.getDefaultInstance().getService();

    // The name for the new bucket
    String bucketName = args[0];  // "my-new-bucket";

    // Creates the new bucket
    Bucket bucket = storage.create(BucketInfo.of(bucketName));

    System.out.printf("Bucket %s created.%n", bucket.getName());
  }
}

Node.js

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

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

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const bucketName = 'bucket-name';

async function createBucket() {
  // Creates the new bucket
  await storage.createBucket(bucketName);
  console.log(`Bucket ${bucketName} created.`);
}

createBucket();

PHP

# Includes the autoloader for libraries installed with composer
require __DIR__ . '/vendor/autoload.php';

# Imports the Google Cloud client library
use Google\Cloud\Storage\StorageClient;

# Your Google Cloud Platform project ID
$projectId = 'YOUR_PROJECT_ID';

# Instantiates a client
$storage = new StorageClient([
    'projectId' => $projectId
]);

# The name for the new bucket
$bucketName = 'my-new-bucket';

# Creates the new bucket
$bucket = $storage->createBucket($bucketName);

echo 'Bucket ' . $bucket->name() . ' created.';

Python

# Imports the Google Cloud client library
from google.cloud import storage

# Instantiates a client
storage_client = storage.Client()

# The name for the new bucket
bucket_name = 'my-new-bucket'

# Creates the new bucket
bucket = storage_client.create_bucket(bucket_name)

print('Bucket {} created.'.format(bucket.name))

Ruby

# Imports the Google Cloud client library
require "google/cloud/storage"

# Your Google Cloud Platform project ID
project_id = "YOUR_PROJECT_ID"

# Instantiates a client
storage = Google::Cloud::Storage.new project_id: project_id

# The name for the new bucket
bucket_name = "my-new-bucket"

# Creates the new bucket
bucket = storage.create_bucket bucket_name

puts "Bucket #{bucket.name} was created."

More Examples

For more examples of using client libraries with Cloud Storage, see the following how-to guides:

Additional resources

此页内容是否有用?请给出您的反馈和评价:

发送以下问题的反馈:

此网页
Cloud Storage
需要帮助?请访问我们的支持页面