Renaming, copying, and moving objects

This page shows you how to rename, copy, and move objects within and between buckets in Cloud Storage. For an overview of objects, read the Key Terms and see the Object naming requirements.

Renaming an object

To rename an existing object in one of your Cloud Storage buckets:

Console

  1. Open the Cloud Storage browser in the Google Cloud Console.
    Open the Cloud Storage browser
  2. In the list of buckets, click on the name of the bucket that contains the object you want to rename.

    The Bucket details page opens, with the Objects tab selected.

  3. Navigate to the object, which may be located in a folder.

  4. Click the more actions menu () associated with the object.

  5. Click Rename.

  6. In the overlay window that appears, enter a new name for the object.

  7. Click Rename.

See Troubleshooting for how to get detailed error information about failed operations in the Cloud Storage browser.

gsutil

Use the gsutil mv command:

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

Where:

  • BUCKET_NAME is the name of the bucket containing the object you want to rename. For example, my-bucket.
  • OLD_OBJECT_NAME is the name of the object you want to rename. For example, pets/dog.png.
  • NEW_OBJECT_NAME is the new name you want to give your object. For example, pets/shiba.png.

If successful, the response looks like the following example:

Operation completed over 1 objects/58.8 KiB.

Code samples

C++

For more information, see the Cloud Storage C++ API reference documentation.

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#

For more information, see the Cloud Storage C# API reference documentation.

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

For more information, see the Cloud Storage Go API reference documentation.

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

For more information, see the Cloud Storage Java API reference documentation.

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 sourceObjectName,
      String targetBucketName,
      String targetObjectName) {
    // 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 sourceObjectName = "your-object-name";

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

    // The ID of your GCS object
    // String targetObjectName = "your-new-object-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Blob blob = storage.get(sourceBucketName, sourceObjectName);
    // Write a copy of the object to the target bucket
    CopyWriter copyWriter = blob.copyTo(targetBucketName, targetObjectName);
    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 "
            + sourceObjectName
            + " from bucket "
            + sourceBucketName
            + " to "
            + targetObjectName
            + " in bucket "
            + copiedBlob.getBucket());
  }
}

Node.js

For more information, see the Cloud Storage Node.js API reference documentation.

/**
 * 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

For more information, see the Cloud Storage PHP API reference documentation.

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

For more information, see the Cloud Storage Python API reference documentation.

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

For more information, see the Cloud Storage Ruby API reference documentation.

# 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 APIs

JSON API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Use cURL to call the JSON API with a POST Object request:

    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"

    Where:

    • OAUTH2_TOKEN is the access token you generated in Step 1.
    • BUCKET_NAME is the name of the bucket containing the object you want to rename. For example, my-bucket.
    • OLD_OBJECT_NAME is the name of the object you want to rename. For example, pets/dog.png.
    • NEW_OBJECT_NAME is the new name you want to give your object. For example, pets/shiba.png.
  3. Use cURL to call the JSON API with a DELETE Object request:

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

    Where:

    • OAUTH2_TOKEN is the access token you generated in Step 1.
    • BUCKET_NAME is the name of the bucket containing the original and renamed object. For example, my-bucket.
    • OLD_OBJECT_NAME is the original name of the object. For example, pets/dog.png.

XML API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Use cURL to call the XML API with a PUT Object request:

    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"

    Where:

    • OAUTH2_TOKEN is the access token you generated in Step 1.
    • BUCKET_NAME is the name of the bucket containing the object you want to rename. For example, my-bucket.
    • OLD_OBJECT_NAME is the name of the object you want to rename. For example, pets/dog.png.
    • NEW_OBJECT_NAME is the new name you want to give your object. For example, pets/shiba.png.
  3. Use cURL to call the XML API with a DELETE Object request:

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

    Where:

    • OAUTH2_TOKEN is the access token you generated in Step 1.
    • BUCKET_NAME is the name of the bucket containing the original and renamed object. For example, my-bucket.
    • OLD_OBJECT_NAME is the original name of the object. For example, pets/dog.png.

Copying an object

To copy an object in one of your Cloud Storage buckets:

Console

  1. Open the Cloud Storage browser in the Google Cloud Console.
    Open the Cloud Storage browser
  2. In the list of buckets, click on the name of the bucket that contains the object you want to copy.

    The Bucket details page opens, with the Objects tab selected.

  3. Navigate to the object, which may be located in a folder.

  4. Click the more actions menu () associated with the object.

  5. Click Copy.

  6. In the overlay window that appears, click Browse.

  7. Select the destination for the copied object and the name for the copied object.

  8. Click Select.

  9. Click Copy.

See Troubleshooting for how to get detailed error information about failed operations in the Cloud Storage browser.

gsutil

Use the gsutil cp command:

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

Where:

  • SOURCE_BUCKET_NAME is the name of the bucket containing the object you want to copy. For example, my-bucket.
  • SOURCE_OBJECT_NAME is the name of the object you want to copy. For example, pets/dog.png.
  • DESTINATION_BUCKET_NAME is the name of the bucket where you want to copy your object. For example, another-bucket.
  • NAME_OF_COPY is the name you want to give the copy of your object. For example, shiba.png.

If successful, the response looks like the following example:

Operation completed over 1 objects/58.8 KiB.

Code samples

C#

For more information, see the Cloud Storage C# API reference documentation.

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

For more information, see the Cloud Storage Go API reference documentation.

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

For more information, see the Cloud Storage Java API reference documentation.

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

For more information, see the Cloud Storage Node.js API reference documentation.

/**
 * 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

For more information, see the Cloud Storage PHP API reference documentation.

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

For more information, see the Cloud Storage Python API reference documentation.

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

For more information, see the Cloud Storage Ruby API reference documentation.

# 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 APIs

JSON API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Use cURL to call the JSON API with a POST Object request:

    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"

    Where:

    • OAUTH2_TOKEN is the name of the access token you generated in Step 1.
    • SOURCE_BUCKET_NAME is the name of the bucket containing the object you want to copy. For example, my-bucket.
    • SOURCE_OBJECT_NAME is the name of the object you want to copy. For example, pets/dog.png.
    • DESTINATION_BUCKET_NAME is the name of the bucket where you want to copy your object. For example, another-bucket.
    • NAME_OF_COPY is the name you want to give the copy of your object. For example, shiba.png.

XML API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Use cURL to call the XML API with a PUT Object request:

    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"

    Where:

    • OAUTH2_TOKEN is the name of the access token you generated in Step 1.
    • SOURCE_BUCKET_NAME is the name of the bucket containing the object you want to copy. For example, my-bucket.
    • SOURCE_OBJECT_NAME is the name of the object you want to copy. For example, pets/dog.png.
    • DESTINATION_BUCKET_NAME is the name of the bucket where you want to copy your object. For example, another-bucket.
    • NAME_OF_COPY is the name you want to give the copy of your object. For example, shiba.png.

Moving an object

To move an object in Cloud Storage:

Console

  1. Open the Cloud Storage browser in the Google Cloud Console.
    Open the Cloud Storage browser
  2. In the list of buckets, click on the name of the bucket that contains the object you want to move.

    The Bucket details page opens, with the Objects tab selected.

  3. Navigate to the object, which may be located in a folder.

  4. Click the more actions menu () associated with the object.

  5. Click Move.

  6. In the overlay window that appears, click Browse.

  7. Select the destination for the object you are moving.

  8. Click Select.

  9. Click Move.

See Troubleshooting for how to get detailed error information about failed operations in the Cloud Storage browser.

gsutil

Use the gsutil mv command:

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

Where:

  • SOURCE_BUCKET_NAME is the name of the bucket containing the object you want to move. For example, my-bucket.
  • SOURCE_OBJECT_NAME is the name of the object you want to move. For example, pets/dog.png.
  • DESTINATION_BUCKET_NAME is the name of the bucket where you want to move your object. For example, another-bucket.
  • DESTINATION_OBJECT_NAME is the name you want to give your object in its new location. For example, shiba.png.

If successful, the response looks like the following example:

Operation completed over 1 objects/58.8 KiB.

Code samples

C++

For more information, see the Cloud Storage C++ API reference documentation.

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

For more information, see the Cloud Storage Go API reference documentation.

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

For more information, see the Cloud Storage Java API reference documentation.

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 sourceObjectName,
      String targetBucketName,
      String targetObjectName) {
    // 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 sourceObjectName = "your-object-name";

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

    // The ID of your GCS object
    // String targetObjectName = "your-new-object-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Blob blob = storage.get(sourceBucketName, sourceObjectName);
    // Write a copy of the object to the target bucket
    CopyWriter copyWriter = blob.copyTo(targetBucketName, targetObjectName);
    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 "
            + sourceObjectName
            + " from bucket "
            + sourceBucketName
            + " to "
            + targetObjectName
            + " in bucket "
            + copiedBlob.getBucket());
  }
}

PHP

For more information, see the Cloud Storage PHP API reference documentation.

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 APIs

JSON API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Use cURL to call the JSON API with a POST Object request:

    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"

    Where:

    • OAUTH2_TOKEN is the name of the access token you generated in Step 1.
    • SOURCE_BUCKET_NAME is the name of the bucket containing the object you want to move. For example, my-bucket.
    • SOURCE_OBJECT_NAME is the name of the object you want to move. For example, pets/dog.png.
    • DESTINATION_BUCKET_NAME is the name of the bucket where you want to move your object. For example, another-bucket.
    • DESTINATION_OBJECT_NAME is the name you want to give your object in its new location. For example, shiba.png.
  3. Use cURL to call the JSON API with a DELETE Object request:

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

    Where:

    • OAUTH2_TOKEN is the access token you generated in Step 1.
    • SOURCE_BUCKET_NAME is the name of the bucket containing the original object. For example, my-bucket.
    • SOURCE_OBJECT_NAME is the name of the original object. For example, pets/dog.png.

XML API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Use cURL to call the XML API with a PUT Object request:

    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"

    Where:

    • OAUTH2_TOKEN is the name of the access token you generated in Step 1.
    • SOURCE_BUCKET_NAME is the name of the bucket containing the object you want to move. For example, my-bucket.
    • SOURCE_OBJECT_NAME is the name of the object you want to move. For example, pets/dog.png.
    • DESTINATION_BUCKET_NAME is the name of the bucket where you want to move your object. For example, another-bucket.
    • DESTINATION_OBJECT_NAME is the name you want to give your object in its new location. For example, shiba.png.
  3. Use cURL to call the JSON API with a DELETE Object request:

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

    Where:

    • OAUTH2_TOKEN is the name of the access token you generated in Step 1.
    • SOURCE_BUCKET_NAME is the name of the bucket containing the original object. For example, my-bucket.
    • SOURCE_OBJECT_NAME is the name of the original object. For example, pets/dog.png.

What's next