ファイル システムからオブジェクトをアップロードする

このページでは、ローカル ファイル システムから Cloud Storage バケットにオブジェクトをアップロードする方法について説明します。アップロードされるオブジェクトは、保存するデータとそれに関連するメタデータから構成されます。ファイルサイズに基づいた最適なアップロード方法を選択する方法など、コンセプトの概要については、アップロードとダウンロードをご覧ください。

メモリからアップロードする手順については、メモリからオブジェクトをアップロードするをご覧ください。

必要なロール

バケットにオブジェクトをアップロードするために必要な権限を取得するには、バケットに対する Storage オブジェクト ユーザー(roles/storage.objectUser)IAM ロールを付与するよう管理者に依頼してください。この事前定義ロールには、バケットにオブジェクトをアップロードするために必要な権限が含まれています。必要とされる正確な権限については、「必要な権限」セクションを開いてご確認ください。

必要な権限

  • storage.objects.create
  • storage.objects.delete
    • この権限は、既存のオブジェクトを上書きするアップロードにのみ必要です。
  • storage.objects.get
    • この権限は、Google Cloud CLI を使用してこのページのタスクを遂行する場合にのみ必要です。
  • storage.objects.list
    • この権限は、Google Cloud CLI を使用してこのページのタスクを遂行する場合にのみ必要です。アップロードしたオブジェクトを Google Cloud コンソールで確認する場合も、この権限が必要です。

Google Cloud コンソールを使用してこのページのタスクを遂行する場合は、storage.buckets.list 権限も必要です。この権限は Storage オブジェクト ユーザー(roles/storage.objectUser)ロールには割り当てられていません。この権限を取得するには、プロジェクトのストレージ管理者(roles/storage.admin)ロールの付与を管理者へ依頼します。

これらの権限は、他の事前定義ロールカスタムロールを使用して取得することもできます。

バケットに対するロールの付与については、バケットでの IAM ポリシーの設定と管理をご覧ください。

バケットにオブジェクトをアップロードする

オブジェクトをバケットにアップロードするには、次の手順を行います。

コンソール

  1. Google Cloud コンソールで Cloud Storage の [バケット] ページに移動します。

    [バケット] に移動

  2. バケットのリストで、オブジェクトをアップロードするバケットの名前をクリックします。

  3. バケットの [オブジェクト] タブで次のいずれかを行います。

    • デスクトップまたはファイル マネージャーから Google Cloud コンソールのメインペインにファイルをドラッグします。

    • [アップロード] > [ファイルをアップロード] をクリックし、表示されたダイアログでアップロードするファイルを選択してから、[開く] をクリックします。

失敗した Cloud Storage オペレーションの詳細なエラー情報を Google Cloud コンソールで確認する方法については、トラブルシューティングをご覧ください。

コマンドライン

gcloud storage cp コマンドを使用します。

gcloud storage cp OBJECT_LOCATION gs://DESTINATION_BUCKET_NAME

各変数の意味は次のとおりです。

  • OBJECT_LOCATION は、オブジェクトへのローカルパスです。たとえば Desktop/dog.png です。

  • DESTINATION_BUCKET_NAME は、オブジェクトをアップロードするバケットの名前です。たとえば my-bucket です。

成功した場合は、次の例のようなレスポンスになります。

Completed files 1/1 | 164.3kiB/164.3kiB

コマンドフラグを使用すると、アップロードしたオブジェクトの一部として、固定キーとカスタム オブジェクト メタデータを設定できます。

クライアント ライブラリ

C++

詳細については、Cloud Storage C++ API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& file_name,
   std::string const& bucket_name, std::string const& object_name) {
  // Note that the client library automatically computes a hash on the
  // client-side to verify data integrity during transmission.
  StatusOr<gcs::ObjectMetadata> metadata = client.UploadFile(
      file_name, bucket_name, object_name, gcs::IfGenerationMatch(0));
  if (!metadata) throw std::move(metadata).status();

  std::cout << "Uploaded " << file_name << " to object " << metadata->name()
            << " in bucket " << metadata->bucket()
            << "\nFull metadata: " << *metadata << "\n";
}

C#

詳細については、Cloud Storage C# API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。


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

public class UploadFileSample
{
    public void UploadFile(
        string bucketName = "your-unique-bucket-name",
        string localPath = "my-local-path/my-file-name",
        string objectName = "my-file-name")
    {
        var storage = StorageClient.Create();
        using var fileStream = File.OpenRead(localPath);
        storage.UploadObject(bucketName, objectName, null, fileStream);
        Console.WriteLine($"Uploaded {objectName}.");
    }
}

Go

詳細については、Cloud Storage Go API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

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

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

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

	// Open local file.
	f, err := os.Open("notes.txt")
	if err != nil {
		return fmt.Errorf("os.Open: %w", err)
	}
	defer f.Close()

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

	o := client.Bucket(bucket).Object(object)

	// Optional: set a generation-match precondition to avoid potential race
	// conditions and data corruptions. The request to upload is aborted if the
	// object's generation number does not match your precondition.
	// For an object that does not yet exist, set the DoesNotExist precondition.
	o = o.If(storage.Conditions{DoesNotExist: true})
	// If the live object already exists in your bucket, set instead a
	// generation-match precondition using the live object's generation number.
	// attrs, err := o.Attrs(ctx)
	// if err != nil {
	// 	return fmt.Errorf("object.Attrs: %w", err)
	// }
	// o = o.If(storage.Conditions{GenerationMatch: attrs.Generation})

	// Upload an object with storage.Writer.
	wc := o.NewWriter(ctx)
	if _, err = io.Copy(wc, f); err != nil {
		return fmt.Errorf("io.Copy: %w", err)
	}
	if err := wc.Close(); err != nil {
		return fmt.Errorf("Writer.Close: %w", err)
	}
	fmt.Fprintf(w, "Blob %v uploaded.\n", object)
	return nil
}

Java

詳細については、Cloud Storage Java API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

次のサンプルでは、個々のオブジェクトをアップロードします。


import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.BlobInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.io.IOException;
import java.nio.file.Paths;

public class UploadObject {
  public static void uploadObject(
      String projectId, String bucketName, String objectName, String filePath) 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 ID of your GCS object
    // String objectName = "your-object-name";

    // The path to your file to upload
    // String filePath = "path/to/your/file"

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    BlobId blobId = BlobId.of(bucketName, objectName);
    BlobInfo blobInfo = BlobInfo.newBuilder(blobId).build();

    // Optional: set a generation-match precondition to avoid potential race
    // conditions and data corruptions. The request returns a 412 error if the
    // preconditions are not met.
    Storage.BlobWriteOption precondition;
    if (storage.get(bucketName, objectName) == null) {
      // For a target object that does not yet exist, set the DoesNotExist precondition.
      // This will cause the request to fail if the object is created before the request runs.
      precondition = Storage.BlobWriteOption.doesNotExist();
    } else {
      // If the destination already exists in your bucket, instead set a generation-match
      // precondition. This will cause the request to fail if the existing object's generation
      // changes before the request runs.
      precondition =
          Storage.BlobWriteOption.generationMatch(
              storage.get(bucketName, objectName).getGeneration());
    }
    storage.createFrom(blobInfo, Paths.get(filePath), precondition);

    System.out.println(
        "File " + filePath + " uploaded to bucket " + bucketName + " as " + objectName);
  }
}

次のサンプルでは、複数のオブジェクトを同時にアップロードします。

import com.google.cloud.storage.transfermanager.ParallelUploadConfig;
import com.google.cloud.storage.transfermanager.TransferManager;
import com.google.cloud.storage.transfermanager.TransferManagerConfig;
import com.google.cloud.storage.transfermanager.UploadResult;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;

class UploadMany {

  public static void uploadManyFiles(String bucketName, List<Path> files) throws IOException {
    TransferManager transferManager = TransferManagerConfig.newBuilder().build().getService();
    ParallelUploadConfig parallelUploadConfig =
        ParallelUploadConfig.newBuilder().setBucketName(bucketName).build();
    List<UploadResult>