重命名、复制和移动对象

本页面介绍了如何在 Cloud Storage 中的存储分区内和存储分区之间重命名、复制和移动对象。如需大致了解各个对象,请参阅关键术语并查看对象命名要求

重命名对象

要重命名其中一个 Cloud Storage 存储分区中的现有对象,请执行以下操作:

控制台

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

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

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

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

  5. 点击重命名

  6. 在出现的叠加窗口中,输入对象的新名称。

  7. 点击重命名

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

gsutil

使用 gsutil mv 命令:

gsutil mv gs://BUCKET_NAME/OLD_OBJECT_NAME gs://BUCKET_NAME/NEW_OBJECT_NAME

其中:

  • BUCKET_NAME 是包含待重命名对象的存储分区的名称。例如 my-bucket
  • OLD_OBJECT_NAME 是待重命名对象的名称。例如 pets/dog.png
  • NEW_OBJECT_NAME 是您要为对象指定的新名称。例如 pets/shiba.png

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

Operation completed over 1 objects/58.8 KiB.

代码示例

C++

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

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& old_object_name, std::string const& new_object_name) {
  StatusOr<gcs::ObjectMetadata> metadata = client.RewriteObjectBlocking(
      bucket_name, old_object_name, bucket_name, new_object_name);
  if (!metadata) throw std::runtime_error(metadata.status().message());

  google::cloud::Status status =
      client.DeleteObject(bucket_name, old_object_name);
  if (!status.ok()) throw std::runtime_error(status.message());

  std::cout << "Renamed " << old_object_name << " to " << new_object_name
            << " in bucket " << bucket_name << "\n";
}

C#

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

private void MoveObject(string bucketName, string sourceObjectName,
    string destObjectName)
{
    var storage = StorageClient.Create();
    storage.CopyObject(bucketName, sourceObjectName, bucketName,
        destObjectName);
    storage.DeleteObject(bucketName, sourceObjectName);
    Console.WriteLine($"Moved {sourceObjectName} to {destObjectName}.");
}

Go

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

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

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

// moveFile moves an object into another location.
func moveFile(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: %v", err)
	}
	defer client.Close()

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

	dstName := object + "-rename"
	src := client.Bucket(bucket).Object(object)
	dst := client.Bucket(bucket).Object(dstName)

	if _, err := dst.CopierFrom(src).Run(ctx); err != nil {
		return fmt.Errorf("Object(%q).CopierFrom(%q).Run: %v", dstName, object, err)
	}
	if err := src.Delete(ctx); err != nil {
		return fmt.Errorf("Object(%q).Delete: %v", object, err)
	}
	fmt.Fprintf(w, "Blob %v moved to %v.\n", object, dstName)
	return nil
}

Java

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

import com.google.cloud.storage.Blob;
import com.google.cloud.storage.CopyWriter;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class MoveObject {
  public static void moveObject(
      String projectId, String sourceBucketName, String objectName, String targetBucketName) {
    // 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 ID of the bucket to move the object objectName to
    // String targetBucketName = "target-object-bucket"

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Blob blob = storage.get(sourceBucketName, objectName);
    // Write a copy of the object to the target bucket
    CopyWriter copyWriter = blob.copyTo(targetBucketName, objectName);
    Blob copiedBlob = copyWriter.getResult();
    // Delete the original blob now that we've copied to where we want it, finishing the "move"
    // operation
    blob.delete();

    System.out.println(
        "Moved object "
            + objectName
            + " from bucket "
            + sourceBucketName
            + " to "
            + copiedBlob.getBucket());
  }
}

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 = 'File to move, e.g. file.txt';
// const destFilename = 'Destination for file, e.g. moved.txt';

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

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

async function moveFile() {
  // Moves the file within the bucket
  await storage.bucket(bucketName).file(srcFilename).move(destFilename);

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

moveFile().catch(console.error);

PHP

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

use Google\Cloud\Storage\StorageClient;

/**
 * Move an object to a new name and/or bucket.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 * @param string $objectName the name of your Cloud Storage object.
 * @param string $newBucketName the destination bucket name.
 * @param string $newObjectName the destination object name.
 *
 * @return void
 */
function move_object($bucketName, $objectName, $newBucketName, $newObjectName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $object->copy($newBucketName, ['name' => $newObjectName]);
    $object->delete();
    printf('Moved gs://%s/%s to gs://%s/%s' . PHP_EOL,
        $bucketName,
        $objectName,
        $newBucketName,
        $newObjectName);
}

Python

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

from google.cloud import storage

def rename_blob(bucket_name, blob_name, new_name):
    """Renames a blob."""
    # bucket_name = "your-bucket-name"
    # blob_name = "your-object-name"
    # new_name = "new-object-name"

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(blob_name)

    new_blob = bucket.rename_blob(blob, new_name)

    print("Blob {} has been renamed to {}".format(blob.name, new_blob.name))

Ruby

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

# bucket_name = "Your Google Cloud Storage bucket name"
# file_name   = "Name of file in Google Cloud Storage to rename"
# new_name    = "File will be renamed to this new name"

require "google/cloud/storage"

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

renamed_file = file.copy new_name

file.delete

puts "#{file_name} has been renamed to #{renamed_file.name}"

REST API

JSON API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 使用 cURL,通过 POST 对象请求调用 JSON API

    curl -X POST \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      -H "Content-Length: 0" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/o/OLD_OBJECT_NAME/rewriteTo/b/BUCKET_NAME/o/NEW_OBJECT_NAME"

    其中:

    • OAUTH2_TOKEN 是您在第 1 步中生成的访问令牌。
    • BUCKET_NAME 是包含待重命名对象的存储分区的名称。例如 my-bucket
    • OLD_OBJECT_NAME 是待重命名对象的名称。例如 pets/dog.png
    • NEW_OBJECT_NAME 是您要为对象指定的新名称。例如 pets/shiba.png
  3. 使用 cURL,通过 DELETE Object 请求调用 JSON API:

    curl -X DELETE \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/o/OLD_OBJECT_NAME"

    其中:

    • OAUTH2_TOKEN 是您在第 1 步中生成的访问令牌。
    • BUCKET_NAME 是包含原始和重命名对象的存储分区的名称。例如 my-bucket
    • OLD_OBJECT_NAME 是对象的原始名称。例如 pets/dog.png

XML API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 使用 cURL,通过 PUT Object 请求调用 XML API

    curl -X PUT \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      -H "x-goog-copy-source: BUCKET_NAME/OLD_OBJECT_NAME" \
      "https://storage.googleapis.com/BUCKET_NAME/NEW_OBJECT_NAME"

    其中:

    • OAUTH2_TOKEN 是您在第 1 步中生成的访问令牌。
    • BUCKET_NAME 是包含待重命名对象的存储分区的名称。例如 my-bucket
    • OLD_OBJECT_NAME 是待重命名对象的名称。例如 pets/dog.png
    • NEW_OBJECT_NAME 是您要为对象指定的新名称。例如 pets/shiba.png
  3. 使用 cURL,通过 DELETE Object 请求调用 XML API:

    curl -X DELETE \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      "https://storage.googleapis.com/BUCKET_NAME/OLD_OBJECT_NAME"

    其中:

    • OAUTH2_TOKEN 是您在第 1 步中生成的访问令牌。
    • BUCKET_NAME 是包含原始和重命名对象的存储分区的名称。例如 my-bucket
    • OLD_OBJECT_NAME 是对象的原始名称。例如 pets/dog.png

复制对象

要复制其中一个 Cloud Storage 存储分区中的对象,请执行以下操作:

控制台

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

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

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

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

  5. 点击复制

  6. 在出现的叠加窗口中,点击浏览

  7. 选择复制对象的目的地和复制对象的名称。

  8. 点击选择

  9. 点击复制

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

gsutil

使用 gsutil cp 命令:

gsutil cp gs://SOURCE_BUCKET_NAME/SOURCE_OBJECT_NAME gs://DESTINATION_BUCKET_NAME/NAME_OF_COPY

其中:

  • SOURCE_BUCKET_NAME 是包含待复制对象的存储分区的名称。例如 my-bucket
  • SOURCE_OBJECT_NAME 是您要复制的对象的名称,例如 pets/dog.png
  • DESTINATION_BUCKET_NAME 是对象要复制到的存储分区的名称。例如 another-bucket
  • NAME_OF_COPY 是您要为对象副本指定的名称。例如 shiba.png

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

Operation completed over 1 objects/58.8 KiB.

代码示例

C#

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

private void CopyObject(string sourceBucketName, string sourceObjectName,
    string destBucketName, string destObjectName)
{
    var storage = StorageClient.Create();
    storage.CopyObject(sourceBucketName, sourceObjectName,
        destBucketName, destObjectName);
    Console.WriteLine($"Copied {sourceBucketName}/{sourceObjectName} to "
        + $"{destBucketName}/{destObjectName}.");
}

Go

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

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

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

// copyFile copies an object into specified bucket.
func copyFile(w io.Writer, dstBucket, srcBucket, srcObject string) error {
	// dstBucket := "bucket-1"
	// srcBucket := "bucket-2"
	// srcObject := "object"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %v", err)
	}
	defer client.Close()

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

	dstObject := srcObject + "-copy"
	src := client.Bucket(srcBucket).Object(srcObject)
	dst := client.Bucket(dstBucket).Object(dstObject)

	if _, err := dst.CopierFrom(src).Run(ctx); err != nil {
		return fmt.Errorf("Object(%q).CopierFrom(%q).Run: %v", dstObject, srcObject, err)
	}
	fmt.Fprintf(w, "Blob %v in bucket %v copied to blob %v in bucket %v.\n", srcObject, srcBucket, dstObject, dstBucket)
	return nil
}

Java

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

import com.google.cloud.storage.Blob;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class CopyObject {
  public static void copyObject(
      String projectId, String sourceBucketName, String objectName, String targetBucketName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of the bucket the original object is in
    // String sourceBucketName = "your-source-bucket";

    // The ID of the GCS object to copy
    // String objectName = "your-object-name";

    // The ID of the bucket to copy the object to
    // String targetBucketName = "target-object-bucket"

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Blob blob = storage.get(sourceBucketName, objectName);

    // This keeps the original name, you could also do
    // copyTo(targetBucketName, "target-object-name") to change the name
    blob.copyTo(targetBucketName);

    System.out.println(
        "Copied object "
            + objectName
            + " from bucket "
            + sourceBucketName
            + " to "
            + targetBucketName);
  }
}

Node.js

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

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const srcBucketName = 'Name of the source bucket, e.g. my-bucket';
// const srcFilename = 'Name of the source file, e.g. file.txt';
// const destBucketName = 'Name of the destination bucket, e.g. my-other-bucket';
// const destFilename = 'Destination name of file, e.g. file.txt';

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

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

async function copyFile() {
  // Copies the file to the other bucket
  await storage
    .bucket(srcBucketName)
    .file(srcFilename)
    .copy(storage.bucket(destBucketName).file(destFilename));

  console.log(
    `gs://${srcBucketName}/${srcFilename} copied to gs://${destBucketName}/${destFilename}.`
  );
}

copyFile().catch(console.error);

PHP

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

use Google\Cloud\Storage\StorageClient;

/**
 * Copy an object to a new name and/or bucket.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 * @param string $objectName the name of your Cloud Storage object.
 * @param string $newBucketName the destination bucket name.
 * @param string $newObjectName the destination object name.
 * @return void
 */
function copy_object($bucketName, $objectName, $newBucketName, $newObjectName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $object->copy($newBucketName, ['name' => $newObjectName]);
    printf('Copied gs://%s/%s to gs://%s/%s' . PHP_EOL,
        $bucketName, $objectName, $newBucketName, $newObjectName);
}

Python

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

from google.cloud import storage

def copy_blob(
    bucket_name, blob_name, destination_bucket_name, destination_blob_name
):
    """Copies a blob from one bucket to another with a new name."""
    # bucket_name = "your-bucket-name"
    # blob_name = "your-object-name"
    # destination_bucket_name = "destination-bucket-name"
    # destination_blob_name = "destination-object-name"

    storage_client = storage.Client()

    source_bucket = storage_client.bucket(bucket_name)
    source_blob = source_bucket.blob(blob_name)
    destination_bucket = storage_client.bucket(destination_bucket_name)

    blob_copy = source_bucket.copy_blob(
        source_blob, destination_bucket, destination_blob_name
    )

    print(
        "Blob {} in bucket {} copied to blob {} in bucket {}.".format(
            source_blob.name,
            source_bucket.name,
            blob_copy.name,
            destination_bucket.name,
        )
    )

Ruby

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

# source_bucket_name = "Source bucket to copy file from"
# source_file_name   = "Source file name"
# dest_bucket_name   = "Destination bucket to copy file to"
# dest_file_name     = "Destination file name"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new
bucket  = storage.bucket source_bucket_name
file    = bucket.file source_file_name

destination_bucket = storage.bucket dest_bucket_name
destination_file   = file.copy destination_bucket.name, dest_file_name

puts "#{file.name} in #{bucket.name} copied to " \
     "#{destination_file.name} in #{destination_bucket.name}"

REST API

JSON API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 使用 cURL,通过 POST 对象请求调用 JSON API

    curl -X POST \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      -H "Content-Length: 0" \
      "https://storage.googleapis.com/storage/v1/b/SOURCE_BUCKET_NAME/o/SOURCE_OBJECT_NAME/rewriteTo/b/DESTINATION_BUCKET_NAME/o/NAME_OF_COPY"

    其中:

    • OAUTH2_TOKEN 是您在第 1 步中生成的访问令牌的名称。
    • SOURCE_BUCKET_NAME 是包含待复制对象的存储分区的名称。例如 my-bucket
    • SOURCE_OBJECT_NAME 是您要复制的对象的名称,例如 pets/dog.png
    • DESTINATION_BUCKET_NAME 是对象要复制到的存储分区的名称。例如 another-bucket
    • NAME_OF_COPY 是您要为对象副本指定的名称。例如 shiba.png

XML API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 使用 cURL,通过 PUT Object 请求调用 XML API

    curl -X PUT \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      -H "x-goog-copy-source: SOURCE_BUCKET_NAME/SOURCE_OBJECT_NAME" \
      "https://storage.googleapis.com/DESTINATION_BUCKET_NAME/NAME_OF_COPY"

    其中:

    • OAUTH2_TOKEN 是您在第 1 步中生成的访问令牌的名称。
    • SOURCE_BUCKET_NAME 是包含待复制对象的存储分区的名称。例如 my-bucket
    • SOURCE_OBJECT_NAME 是您要复制的对象的名称,例如 pets/dog.png
    • DESTINATION_BUCKET_NAME 是对象要复制到的存储分区的名称。例如 another-bucket
    • NAME_OF_COPY 是您要为对象副本指定的名称。例如 shiba.png

移动对象

要移动 Cloud Storage 中的对象,请执行以下操作:

控制台

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

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

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

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

  5. 点击移动

  6. 在出现的叠加窗口中,点击浏览

  7. 选择对象要移动到的目的地。

  8. 点击选择

  9. 点击移动

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

gsutil

使用 gsutil mv 命令:

gsutil mv gs://SOURCE_BUCKET_NAME/SOURCE_OBJECT_NAME gs://DESTINATION_BUCKET_NAME/DESTINATION_OBJECT_NAME

其中:

  • SOURCE_BUCKET_NAME 是包含待移动对象的存储分区的名称。例如 my-bucket
  • SOURCE_OBJECT_NAME 是待移动对象的名称。例如 pets/dog.png
  • DESTINATION_BUCKET_NAME 是对象要移动到的存储分区的名称。例如 another-bucket
  • DESTINATION_OBJECT_NAME 是您要在新位置为对象指定的名称。例如 shiba.png

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

Operation completed over 1 objects/58.8 KiB.

代码示例

C++

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

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& old_object_name, std::string const& new_object_name) {
  StatusOr<gcs::ObjectMetadata> metadata = client.RewriteObjectBlocking(
      bucket_name, old_object_name, bucket_name, new_object_name);
  if (!metadata) throw std::runtime_error(metadata.status().message());

  google::cloud::Status status =
      client.DeleteObject(bucket_name, old_object_name);
  if (!status.ok()) throw std::runtime_error(status.message());

  std::cout << "Renamed " << old_object_name << " to " << new_object_name
            << " in bucket " << bucket_name << "\n";
}

Go

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

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

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

// moveFile moves an object into another location.
func moveFile(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: %v", err)
	}
	defer client.Close()

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

	dstName := object + "-rename"
	src := client.Bucket(bucket).Object(object)
	dst := client.Bucket(bucket).Object(dstName)

	if _, err := dst.CopierFrom(src).Run(ctx); err != nil {
		return fmt.Errorf("Object(%q).CopierFrom(%q).Run: %v", dstName, object, err)
	}
	if err := src.Delete(ctx); err != nil {
		return fmt.Errorf("Object(%q).Delete: %v", object, err)
	}
	fmt.Fprintf(w, "Blob %v moved to %v.\n", object, dstName)
	return nil
}

Java

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

import com.google.cloud.storage.Blob;
import com.google.cloud.storage.CopyWriter;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class MoveObject {
  public static void moveObject(
      String projectId, String sourceBucketName, String objectName, String targetBucketName) {
    // 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 ID of the bucket to move the object objectName to
    // String targetBucketName = "target-object-bucket"

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Blob blob = storage.get(sourceBucketName, objectName);
    // Write a copy of the object to the target bucket
    CopyWriter copyWriter = blob.copyTo(targetBucketName, objectName);
    Blob copiedBlob = copyWriter.getResult();
    // Delete the original blob now that we've copied to where we want it, finishing the "move"
    // operation
    blob.delete();

    System.out.println(
        "Moved object "
            + objectName
            + " from bucket "
            + sourceBucketName
            + " to "
            + copiedBlob.getBucket());
  }
}

PHP

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

use Google\Cloud\Storage\StorageClient;

/**
 * Move an object to a new name and/or bucket.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 * @param string $objectName the name of your Cloud Storage object.
 * @param string $newBucketName the destination bucket name.
 * @param string $newObjectName the destination object name.
 *
 * @return void
 */
function move_object($bucketName, $objectName, $newBucketName, $newObjectName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $object->copy($newBucketName, ['name' => $newObjectName]);
    $object->delete();
    printf('Moved gs://%s/%s to gs://%s/%s' . PHP_EOL,
        $bucketName,
        $objectName,
        $newBucketName,
        $newObjectName);
}

REST API

JSON API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 使用 cURL,通过 POST 对象请求调用 JSON API

    curl -X POST \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      -H "Content-Length: 0" \
      "https://storage.googleapis.com/storage/v1/b/SOURCE_BUCKET_NAME/o/SOURCE_OBJECT_NAME/rewriteTo/b/DESTINATION_BUCKET_NAME/o/DESTINATION_OBJECT_NAME"

    其中:

    • OAUTH2_TOKEN 是您在第 1 步中生成的访问令牌的名称。
    • SOURCE_BUCKET_NAME 是包含待移动对象的存储分区的名称。例如 my-bucket
    • SOURCE_OBJECT_NAME 是待移动对象的名称。例如 pets/dog.png
    • DESTINATION_BUCKET_NAME 是对象要移动到的存储分区的名称。例如 another-bucket
    • DESTINATION_OBJECT_NAME 是您要在新位置为对象指定的名称。例如 shiba.png
  3. 使用 cURL,通过 DELETE Object 请求调用 JSON API:

    curl -X DELETE \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      "https://storage.googleapis.com/storage/v1/b/SOURCE_BUCKET_NAME/o/SOURCE_OBJECT_NAME"

    其中:

    • OAUTH2_TOKEN 是您在第 1 步中生成的访问令牌。
    • SOURCE_BUCKET_NAME 是包含原始对象的存储分区的名称。例如 my-bucket
    • SOURCE_OBJECT_NAME 是原始对象的名称。例如 pets/dog.png

XML API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 使用 cURL,通过 PUT Object 请求调用 XML API

    curl -X PUT \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      -H "x-goog-copy-source: SOURCE_BUCKET_NAME/SOURCE_OBJECT_NAME" \
      "https://storage.googleapis.com/DESTINATION_BUCKET_NAME/DESTINATION_OBJECT_NAME"

    其中:

    • OAUTH2_TOKEN 是您在第 1 步中生成的访问令牌的名称。
    • SOURCE_BUCKET_NAME 是包含待移动对象的存储分区的名称。例如 my-bucket
    • SOURCE_OBJECT_NAME 是待移动对象的名称。例如 pets/dog.png
    • DESTINATION_BUCKET_NAME 是对象要移动到的存储分区的名称。例如 another-bucket
    • DESTINATION_OBJECT_NAME 是您要在新位置为对象指定的名称。例如 shiba.png
  3. 使用 cURL,通过 DELETE Object 请求调用 JSON API:

    curl -X DELETE \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      "https://storage.googleapis.com/SOURCE_BUCKET_NAME/SOURCE_OBJECT_NAME"

    其中:

    • OAUTH2_TOKEN 是您在第 1 步中生成的访问令牌的名称。
    • SOURCE_BUCKET_NAME 是包含原始对象的存储分区的名称。例如 my-bucket
    • SOURCE_OBJECT_NAME 是原始对象的名称。例如 pets/dog.png

后续步骤