Copiare, rinominare e spostare oggetti

Questa pagina mostra come copiare, rinominare e spostare gli oggetti. Mentre alcuni strumenti eseguono operazioni di spostamento atomico degli oggetti, altri simulano un'operazione di spostamento degli oggetti copiando l'oggetto in una nuova posizione specificata ed eliminando l'oggetto originale.

Ti consigliamo di utilizzare Storage Transfer Service per spostare più di 1 TB di dati tra i bucket.

Prima di iniziare

Per copiare, rinominare o spostare gli oggetti, devi ottenere i ruoli IAM richiesti. Le seguenti sezioni descrivono i requisiti IAM per diversi casi d'uso.

Copiare oggetti (inclusi lo spostamento o la ridenominazione tramite copia)

Per ottenere le autorizzazioni necessarie per copiare gli oggetti, chiedi all'amministratore di concederti i seguenti ruoli IAM nel bucket di origine che contiene gli oggetti che vuoi spostare o nel bucket di destinazione in cui vuoi spostare gli oggetti:

  • Storage Object Viewer (roles/storage.objectViewer) nel bucket di origine
  • Storage Object User (roles/storage.objectUser) sul bucket di destinazione
  • Per copiare gli oggetti utilizzando la console Google Cloud : Ruolo di base Visualizzatore (roles/viewer) sia nel bucket di origine che in quello di destinazione, oltre a roles/storage.objectViewer e roles/storage.objectUser

Questi ruoli predefiniti contengono le autorizzazioni necessarie per copiare gli oggetti. Per vedere quali sono esattamente le autorizzazioni richieste, espandi la sezione Autorizzazioni obbligatorie:

Autorizzazioni obbligatorie

Per copiare gli oggetti sono necessarie le seguenti autorizzazioni:

  • storage.objects.get nel bucket di origine
  • storage.objects.create nel bucket di destinazione
  • storage.objects.delete (obbligatorio solo se stai sostituendo o sovrascrivendo un oggetto nel bucket di destinazione nell'ambito di un'operazione di copia o spostamento di oggetti) nel bucket di destinazione
  • storage.objects.delete (obbligatorio solo se sposti un oggetto utilizzando un'operazione di copia ed eliminazione sottostante) nel bucket di origine
  • storage.folders.create (obbligatorio solo se l'oggetto che stai spostando si trova in una cartella che vuoi creare nel bucket di destinazione) nel bucket di destinazione
  • storage.objects.list (obbligatorio solo se stai copiando, spostando o rinominando un oggetto utilizzando la console Google Cloud ) sui bucket di origine e destinazione
  • storage.buckets.list (obbligatorio solo se copi, sposti o rinomini un oggetto utilizzando la console Google Cloud ) nel progetto che contiene i bucket di origine e di destinazione

Puoi anche ottenere queste autorizzazioni con ruoli personalizzati.

Per informazioni sulla concessione dei ruoli sui bucket, consulta Utilizzare IAM con i bucket. Per informazioni sulla concessione dei ruoli nei progetti, consulta Gestire l'accesso ai progetti.

Se l'oggetto che vuoi copiare ha determinate funzionalità attive, potresti aver bisogno di ruoli aggiuntivi o alternativi. Ad esempio, se l'oggetto che vuoi copiare ha una configurazione di conservazione degli oggetti che vuoi mantenere, devi disporre di un ruolo nel bucket di destinazione che includa l'autorizzazione storage.objects.setRetention, ad esempio il ruolo Amministratore oggetti archiviazione (roles/storage.objectAdmin). Per maggiori informazioni, consulta Autorizzazioni IAM per Cloud Storage.

Rinomina gli oggetti in modo atomico

Per ottenere le autorizzazioni necessarie per rinominare gli oggetti in modo atomico, chiedi all'amministratore di concederti il ruolo IAM Utente oggetti Storage (roles/storage.objectUser) nel bucket che contiene l'oggetto che vuoi rinominare.

Questo ruolo predefinito contiene le autorizzazioni necessarie per rinominare gli oggetti in modo atomico. Per vedere quali sono esattamente le autorizzazioni richieste, espandi la sezione Autorizzazioni obbligatorie:

Autorizzazioni obbligatorie

Per rinominare gli oggetti in modo atomico sono necessarie le seguenti autorizzazioni:

  • storage.objects.move
  • storage.objects.create
  • storage.objects.delete (obbligatorio solo se stai sovrascrivendo o sostituendo un oggetto)

Puoi anche ottenere queste autorizzazioni con ruoli personalizzati.

Per informazioni sulla concessione dei ruoli sui bucket, consulta Utilizzare IAM con i bucket.

Copiare oggetti

Questa sezione descrive come copiare gli oggetti. Puoi copiare oggetti da un bucket a un altro.

Console

  1. Nella console Google Cloud , vai alla pagina Bucket in Cloud Storage.

    Vai a Bucket

  2. Nell'elenco dei bucket, fai clic sul nome del bucket che contiene l'oggetto da copiare.

    Viene visualizzata la pagina Dettagli bucket, con la scheda Oggetti selezionata.

  3. Vai all'oggetto, che potrebbe trovarsi in una cartella.

  4. Fai clic sul menu Extra oggetto () associato all'oggetto.

  5. Fai clic su Copia.

    Viene visualizzato il riquadro Copia oggetto.

  6. Nel campo Destinazione, digita il nome del bucket di destinazione e il nome dell'oggetto copiato.

    In alternativa, puoi fare clic su Sfoglia per selezionare la destinazione, ma le opzioni di navigazione sono limitate ai bucket del progetto corrente.

  7. Fai clic su Copia.

Per scoprire come ottenere informazioni dettagliate sugli errori relativi alle operazioni di Cloud Storage non riuscite nella console Google Cloud , consulta Risoluzione dei problemi.

Riga di comando

Utilizza il comando gcloud storage cp:

gcloud storage cp gs://SOURCE_BUCKET_NAME/SOURCE_OBJECT_NAME gs://DESTINATION_BUCKET_NAME/NAME_OF_COPY

Dove:

  • SOURCE_BUCKET_NAME è il nome del bucket che contiene l'oggetto da copiare. Ad esempio, my-bucket.
  • SOURCE_OBJECT_NAME è il nome dell'oggetto che vuoi copiare. Ad esempio, pets/dog.png.
  • DESTINATION_BUCKET_NAME è il nome del bucket in cui vuoi copiare l'oggetto. Ad esempio, another-bucket.
  • NAME_OF_COPY è il nome che vuoi assegnare alla copia dell'oggetto. Ad esempio, shiba.png.

Se l'operazione ha esito positivo, la risposta è simile all'esempio seguente:

Copying gs://example-bucket/file.txt to gs://other-bucket/file-copy.txt
  Completed files 1/1 | 164.3kiB/164.3kiB 

Librerie client

C++

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Cloud Storage C++.

Per eseguire l'autenticazione in Cloud Storage, configura le Credenziali predefinite dell'applicazione. Per saperne di più, vedi Configurare l'autenticazione per le librerie client.

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& source_bucket_name,
   std::string const& source_object_name,
   std::string const& destination_bucket_name,
   std::string const& destination_object_name) {
  StatusOr<gcs::ObjectMetadata> new_copy_meta =
      client.CopyObject(source_bucket_name, source_object_name,
                        destination_bucket_name, destination_object_name);
  if (!new_copy_meta) throw std::move(new_copy_meta).status();

  std::cout << "Successfully copied " << source_object_name << " in bucket "
            << source_bucket_name << " to bucket " << new_copy_meta->bucket()
            << " with name " << new_copy_meta->name()
            << ".\nThe full metadata after the copy is: " << *new_copy_meta
            << "\n";
}

C#

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Cloud Storage C#.

Per eseguire l'autenticazione in Cloud Storage, configura le Credenziali predefinite dell'applicazione. Per saperne di più, vedi Configurare l'autenticazione per le librerie client.


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

public class CopyFileSample
{
    public void CopyFile(
        string sourceBucketName = "source-bucket-name",
        string sourceObjectName = "source-file",
        string destBucketName = "destination-bucket-name",
        string destObjectName = "destination-file-name")
    {
        var storage = StorageClient.Create();
        storage.CopyObject(sourceBucketName, sourceObjectName, destBucketName, destObjectName);

        Console.WriteLine($"Copied {sourceBucketName}/{sourceObjectName} to " + $"{destBucketName}/{destObjectName}.");
    }
}

Go

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Cloud Storage Go.

Per eseguire l'autenticazione in Cloud Storage, configura le Credenziali predefinite dell'applicazione. Per saperne di più, vedi Configurare l'autenticazione per le librerie client.

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: %w", 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)

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

	if _, err := dst.CopierFrom(src).Run(ctx); err != nil {
		return fmt.Errorf("Object(%q).CopierFrom(%q).Run: %w", 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

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Cloud Storage Java.

Per eseguire l'autenticazione in Cloud Storage, configura le Credenziali predefinite dell'applicazione. Per saperne di più, vedi Configurare l'autenticazione per le librerie client.


import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.BlobInfo;
import com.google.cloud.storage.CopyWriter;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.Storage.CopyRequest;
import com.google.cloud.storage.StorageOptions;

public class CopyObject {
  public static void copyObject(
      String projectId, String sourceBucketName, String objectName, String targetBucketName)
      throws Exception {
    // 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";

    try (Storage storage =
        StorageOptions.newBuilder().setProjectId(projectId).build().getService()) {
      BlobId sourceId = BlobId.of(sourceBucketName, objectName);
      // you could change "objectName" to rename the object
      BlobId targetId = BlobId.of(targetBucketName, objectName);

      // Recommended: 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.BlobTargetOption precondition;
      BlobInfo existingTarget = storage.get(targetBucketName, objectName);
      if (existingTarget == 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.BlobTargetOption.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.BlobTargetOption.generationMatch(existingTarget.getGeneration());
      }

      CopyRequest copyRequest =
          CopyRequest.newBuilder()
              .setSource(sourceId)
              .setTarget(targetId, precondition)
              // limit the number of bytes Cloud Storage will attempt to copy before responding to
              // an individual request.
              // If you see Read Timeout errors, try reducing this value.
              .setMegabytesCopiedPerChunk(2048L) // 2GiB
              .build();
      CopyWriter copyWriter = storage.copy(copyRequest);
      BlobInfo successfulCopyResult = copyWriter.getResult();

      System.out.printf(
          "Copied object gs://%s/%s to %s%n",
          sourceBucketName,
          objectName,
          successfulCopyResult.getBlobId().toGsUtilUriWithGeneration());
    }
  }
}

Node.js

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Cloud Storage Node.js.

Per eseguire l'autenticazione in Cloud Storage, configura le Credenziali predefinite dell'applicazione. Per saperne di più, vedi Configurare l'autenticazione per le librerie client.

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of the bucket the original file is in
// const srcBucketName = 'your-source-bucket';

// The ID of the GCS file to copy
// const srcFilename = 'your-file-name';

// The ID of the bucket to copy the file to
// const destBucketName = 'target-file-bucket';

// The ID of the GCS file to create
// const destFileName = 'target-file-name';

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

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

async function copyFile() {
  const copyDestination = storage.bucket(destBucketName).file(destFileName);

  // Optional:
  // Set a generation-match precondition to avoid potential race conditions
  // and data corruptions. The request to copy is aborted if the object's
  // generation number does not match your precondition. For a destination
  // object that does not yet exist, set the ifGenerationMatch precondition to 0
  // If the destination object already exists in your bucket, set instead a
  // generation-match precondition using its generation number.
  const copyOptions = {
    preconditionOpts: {
      ifGenerationMatch: destinationGenerationMatchPrecondition,
    },
  };

  // Copies the file to the other bucket
  await storage
    .bucket(srcBucketName)
    .file(srcFilename)
    .copy(copyDestination, copyOptions);

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

copyFile().catch(console.error);

PHP

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Cloud Storage PHP.

Per eseguire l'autenticazione in Cloud Storage, configura le Credenziali predefinite dell'applicazione. Per saperne di più, vedi Configurare l'autenticazione per le librerie client.

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.
 *        (e.g. 'my-bucket')
 * @param string $objectName The name of your Cloud Storage object.
 *        (e.g. 'my-object')
 * @param string $newBucketName The destination bucket name.
 *        (e.g. 'my-other-bucket')
 * @param string $newObjectName The destination object name.
 *        (e.g. 'my-other-object')
 */
function copy_object(string $bucketName, string $objectName, string $newBucketName, string $newObjectName): void
{
    $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

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Cloud Storage Python.

Per eseguire l'autenticazione in Cloud Storage, configura le Credenziali predefinite dell'applicazione. Per saperne di più, vedi Configurare l'autenticazione per le librerie client.

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)

    # Optional: set a generation-match precondition to avoid potential race conditions
    # and data corruptions. The request to copy is aborted if the object's
    # generation number does not match your precondition. For a destination
    # object that does not yet exist, set the if_generation_match precondition to 0.
    # If the destination object already exists in your bucket, set instead a
    # generation-match precondition using its generation number.
    # There is also an `if_source_generation_match` parameter, which is not used in this example.
    destination_generation_match_precondition = 0

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

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

Ruby

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Cloud Storage Ruby.

Per eseguire l'autenticazione in Cloud Storage, configura le Credenziali predefinite dell'applicazione. Per saperne di più, vedi Configurare l'autenticazione per le librerie client.

def copy_file source_bucket_name:, source_file_name:, destination_bucket_name:, destination_file_name:
  # The ID of the bucket the original object is in
  # source_bucket_name = "source-bucket-name"

  # The ID of the GCS object to copy
  # source_file_name = "source-file-name"

  # The ID of the bucket to copy the object to
  # destination_bucket_name = "destination-bucket-name"

  # The ID of the new GCS object
  # destination_file_name = "destination-file-name"

  require "google/cloud/storage"

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

  destination_bucket = storage.bucket destination_bucket_name
  destination_file   = file.copy destination_bucket.name, destination_file_name

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

API REST

API JSON

  1. Avere la gcloud CLI installata e inizializzata, che ti consente di generare un token di accesso per l'intestazione Authorization.

  2. Utilizza cURL per chiamare l'API JSON con una richiesta di POSToggetto:

    curl -X POST \
      -H "Authorization: Bearer $(gcloud auth print-access-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"

    Dove:

    • SOURCE_BUCKET_NAME è il nome del bucket contenente l'oggetto da copiare. Ad esempio, my-bucket.
    • SOURCE_OBJECT_NAME è il nome con codifica URL dell'oggetto che vuoi copiare. Ad esempio, pets/dog.png, codificato come URL pets%2Fdog.png.
    • DESTINATION_BUCKET_NAME è il nome del bucket in cui vuoi copiare l'oggetto. Ad esempio, another-bucket.
    • NAME_OF_COPY è il nome con codifica URL che vuoi assegnare alla copia dell'oggetto. Ad esempio, shiba.png.

    Poiché il metodo rewrite copia i dati in blocchi di dimensioni limitate, la copia potrebbe richiedere più richieste, soprattutto per gli oggetti di grandi dimensioni.

    Ad esempio, la seguente risposta a una richiesta rewrite indica che devi effettuare ulteriori richieste rewrite:

    {
      "kind": "storage#rewriteResponse",
      "totalBytesRewritten": 1048576,
      "objectSize": 10000000000,
      "done": false,
      "rewriteToken": TOKEN_VALUE
    }
  3. Utilizza rewriteToken in una richiesta successiva per continuare a copiare i dati:

    curl -X POST \
     -H "Authorization: Bearer $(gcloud auth print-access-token)" \
     -H "Content-Length: 0" \
     -d '{"rewriteToken": "TOKEN_VALUE"}' \
     "https://storage.googleapis.com/storage/v1/b/SOURCE_BUCKET_NAME/o/SOURCE_OBJECT_NAME/rewriteTo/b/DESTINATION_BUCKET_NAME/o/NAME_OF_COPY"

    Dove:

    • TOKEN_VALUE è il valore di rewriteToken restituito nella richiesta precedente.
    • Tutti gli altri valori corrispondono a quelli utilizzati nella richiesta precedente.

    Quando l'oggetto viene copiato completamente, l'ultima risposta ha una proprietà done impostata su true, non esiste una proprietà rewriteToken e i metadati della copia sono inclusi nella proprietà resource.

    {
     "kind": "storage#rewriteResponse",
     "totalBytesRewritten": 10000000000,
     "objectSize": 10000000000,
     "done": true,
     "resource": objects Resource
    }

API XML

  1. Avere la gcloud CLI installata e inizializzata, che ti consente di generare un token di accesso per l'intestazione Authorization.

  2. Utilizza cURL per chiamare l'API XML con una richiesta di PUT oggetto:

    curl -X PUT \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "x-goog-copy-source: SOURCE_BUCKET_NAME/SOURCE_OBJECT_NAME" \
      "https://storage.googleapis.com/DESTINATION_BUCKET_NAME/NAME_OF_COPY"

    Dove:

    • SOURCE_BUCKET_NAME è il nome del bucket contenente l'oggetto da copiare. Ad esempio, my-bucket.
    • SOURCE_OBJECT_NAME è il nome dell'oggetto che vuoi copiare. Ad esempio, pets/dog.png.
    • DESTINATION_BUCKET_NAME è il nome del bucket in cui vuoi copiare l'oggetto. Ad esempio, another-bucket.
    • NAME_OF_COPY è il nome con codifica URL che vuoi assegnare alla copia dell'oggetto. Ad esempio, shiba.png.

Spostare o rinominare gli oggetti copiandoli

Questa sezione descrive come spostare o rinominare gli oggetti utilizzando le operazioni di copia degli oggetti sottostanti. Gli strumenti descritti in questa sezione eseguono spostamenti e ridenominazioni di oggetti copiando l'oggetto originale in un altro spazio dei nomi ed eliminandolo.

Console

  1. Nella console Google Cloud , vai alla pagina Bucket in Cloud Storage.

    Vai a Bucket

  2. Nell'elenco dei bucket, fai clic sul nome del bucket contenente l'oggetto da spostare.

    Viene visualizzata la pagina Dettagli bucket, con la scheda Oggetti selezionata.

  3. Vai all'oggetto, che potrebbe trovarsi in una cartella.

  4. Fai clic sul menu Extra oggetto () associato all'oggetto.

  5. Se vuoi assegnare un nuovo nome all'oggetto nello stesso bucket, fai clic su Rinomina.

    1. Nella finestra di overlay visualizzata, inserisci un nuovo nome per l'oggetto.

    2. Fai clic su Rinomina.

  6. Se vuoi spostare l'oggetto in un altro bucket, fai clic su Sposta.

    1. Nella finestra di overlay visualizzata, fai clic su Sfoglia.

    2. Seleziona la destinazione dell'oggetto che stai spostando.

    3. Fai clic su Seleziona.

    4. Fai clic su Sposta.

Per scoprire come ottenere informazioni dettagliate sugli errori relativi alle operazioni di Cloud Storage non riuscite nella console Google Cloud , consulta Risoluzione dei problemi.

Riga di comando

Utilizza il comando gcloud storage mv:

gcloud storage mv gs://SOURCE_BUCKET_NAME/SOURCE_OBJECT_NAME gs://DESTINATION_BUCKET_NAME/DESTINATION_OBJECT_NAME

Dove:

  • SOURCE_BUCKET_NAME è il nome del bucket che contiene l'oggetto da spostare o rinominare. Ad esempio, my-bucket.
  • SOURCE_OBJECT_NAME è il nome dell'oggetto che vuoi spostare o rinominare. Ad esempio, pets/dog.png.
  • DESTINATION_BUCKET_NAME è il nome del bucket in cui vuoi spostare l'oggetto. Ad esempio, another-bucket.
  • DESTINATION_OBJECT_NAME è il nome che vuoi assegnare all'oggetto dopo lo spostamento o la ridenominazione. Ad esempio, shiba.png.

Se l'operazione ha esito positivo, la risposta è simile all'esempio seguente:

Copying gs://example-bucket/old-file.txt to gs://new-bucket/new-file.txt
Removing gs://example-bucket/old-file.txt...
  Completed files 1/1 | 164.3kiB/164.3kiB 

Librerie client

C++

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Cloud Storage C++.

Per eseguire l'autenticazione in Cloud Storage, configura le Credenziali predefinite dell'applicazione. Per saperne di più, vedi Configurare l'autenticazione per le librerie client.

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::move(metadata).status();

  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#

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Cloud Storage C#.

Per eseguire l'autenticazione in Cloud Storage, configura le Credenziali predefinite dell'applicazione. Per saperne di più, vedi Configurare l'autenticazione per le librerie client.


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

public class MoveFileSample
{
    public void MoveFile(
        string sourceBucketName = "your-unique-bucket-name",
        string sourceObjectName = "your-object-name",
        string targetBucketName = "target-object-bucket",
        string targetObjectName = "target-object-name")
    {
        var storage = StorageClient.Create();
        storage.CopyObject(sourceBucketName, sourceObjectName, targetBucketName, targetObjectName);
        storage.DeleteObject(sourceBucketName, sourceObjectName);
        Console.WriteLine($"Moved {sourceObjectName} to {targetObjectName}.");
    }
}

Go

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Cloud Storage Go.

Per eseguire l'autenticazione in Cloud Storage, configura le Credenziali predefinite dell'applicazione. Per saperne di più, vedi Configurare l'autenticazione per le librerie client.

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: %w", 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)

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

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

Java

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Cloud Storage Java.

Per eseguire l'autenticazione in Cloud Storage, configura le Credenziali predefinite dell'applicazione. Per saperne di più, vedi Configurare l'autenticazione per le librerie client.


import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobId;
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();
    BlobId source = BlobId.of(sourceBucketName, sourceObjectName);
    BlobId target = BlobId.of(targetBucketName, targetObjectName);

    // 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.BlobTargetOption precondition;
    if (storage.get(targetBucketName, targetObjectName) == 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.BlobTargetOption.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.BlobTargetOption.generationMatch(
              storage.get(targetBucketName, targetObjectName).getGeneration());
    }

    // Copy source object to target object
    storage.copy(
        Storage.CopyRequest.newBuilder().setSource(source).setTarget(target, precondition).build());
    Blob copiedObject = storage.get(target);
    // Delete the original blob now that we've copied to where we want it, finishing the "move"
    // operation
    storage.get(source).delete();

    System.out.println(
        "Moved object "
            + sourceObjectName
            + " from bucket "
            + sourceBucketName
            + " to "
            + targetObjectName
            + " in bucket "
            + copiedObject.getBucket());
  }
}

Node.js

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Cloud Storage Node.js.

Per eseguire l'autenticazione in Cloud Storage, configura le Credenziali predefinite dell'applicazione. Per saperne di più, vedi Configurare l'autenticazione per le librerie client.

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-source-bucket';

// The ID of your GCS file
// const srcFileName = 'your-file-name';

// The new ID for your GCS file
// const destFileName = 'your-new-file-name';

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

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

async function moveFile() {
  // Optional:
  // Set a generation-match precondition to avoid potential race conditions
  // and data corruptions. The request to copy is aborted if the object's
  // generation number does not match your precondition. For a destination
  // object that does not yet exist, set the ifGenerationMatch precondition to 0
  // If the destination object already exists in your bucket, set instead a
  // generation-match precondition using its generation number.
  const moveOptions = {
    preconditionOpts: {
      ifGenerationMatch: destinationGenerationMatchPrecondition,
    },
  };

  // Moves the file within the bucket
  await storage
    .bucket(bucketName)
    .file(srcFileName)
    .move(destFileName, moveOptions);

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

moveFile().catch(console.error);

PHP

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Cloud Storage PHP.

Per eseguire l'autenticazione in Cloud Storage, configura le Credenziali predefinite dell'applicazione. Per saperne di più, vedi Configurare l'autenticazione per le librerie client.

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.
 *        (e.g. 'my-bucket')
 * @param string $objectName The name of your Cloud Storage object.
 *        (e.g. 'my-object')
 * @param string $newBucketName the destination bucket name.
 *        (e.g. 'my-other-bucket')
 * @param string $newObjectName the destination object name.
 *        (e.g. 'my-other-object')
 */
function move_object(string $bucketName, string $objectName, string $newBucketName, string $newObjectName): void
{
    $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

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Cloud Storage Python.

Per eseguire l'autenticazione in Cloud Storage, configura le Credenziali predefinite dell'applicazione. Per saperne di più, vedi Configurare l'autenticazione per le librerie client.

from google.cloud import storage


def move_blob(bucket_name, blob_name, destination_bucket_name, destination_blob_name,):
    """Moves a blob from one bucket to another with a new name."""
    # The ID of your GCS bucket
    # bucket_name = "your-bucket-name"
    # The ID of your GCS object
    # blob_name = "your-object-name"
    # The ID of the bucket to move the object to
    # destination_bucket_name = "destination-bucket-name"
    # The ID of your new GCS object (optional)
    # 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)

    # Optional: set a generation-match precondition to avoid potential race conditions
    # and data corruptions. The request is aborted if the object's
    # generation number does not match your precondition. For a destination
    # object that does not yet exist, set the if_generation_match precondition to 0.
    # If the destination object already exists in your bucket, set instead a
    # generation-match precondition using its generation number.
    # There is also an `if_source_generation_match` parameter, which is not used in this example.
    destination_generation_match_precondition = 0

    blob_copy = source_bucket.copy_blob(
        source_blob, destination_bucket, destination_blob_name, if_generation_match=destination_generation_match_precondition,
    )
    source_bucket.delete_blob(blob_name)

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

Ruby

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Cloud Storage Ruby.

Per eseguire l'autenticazione in Cloud Storage, configura le Credenziali predefinite dell'applicazione. Per saperne di più, vedi Configurare l'autenticazione per le librerie client.

def move_file bucket_name:, file_name:, new_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  # The ID of your GCS object
  # file_name = "your-file-name"

  # The ID of your new GCS object
  # new_name = "your-new-file-name"

  require "google/cloud/storage"

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

  renamed_file = file.copy new_name

  file.delete

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

API REST

API JSON

Per istruzioni sull'API JSON per spostare o rinominare oggetti mediante la copia, consulta Copiare oggetti.

API XML

Per le istruzioni dell'API XML sullo spostamento o la ridenominazione di oggetti mediante la copia, consulta Copiare oggetti.

Rinomina gli oggetti in modo atomico

Questa sezione descrive come rinominare in modo atomico gli oggetti all'interno di un bucket. Per rinominare un oggetto, puoi utilizzare il metodo Objects: move nell'API Cloud Storage JSON.

API REST

API JSON

Per rinominare in modo atomico un oggetto:

  1. Avere la gcloud CLI installata e inizializzata, che ti consente di generare un token di accesso per l'intestazione Authorization.

  2. Utilizza cURL per chiamare l'API JSON con una richiesta Objects: move:

    curl -X POST 
    -H "Authorization: Bearer $(gcloud auth print-access-token)"
    -H "Content-Length: 0"
    "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/o/SOURCE_OBJECT_NAME/moveTo/o/DESTINATION_OBJECT_NAME"

    Dove:

    • BUCKET_NAME è il nome del bucket contenente l'oggetto da rinominare. Ad esempio, my-bucket.
    • SOURCE_OBJECT_NAME è il nome con codifica URL dell'oggetto che vuoi rinominare. Ad esempio, pets/dog.png, codificato come URL pets%2Fdog.png.
    • DESTINATION_OBJECT_NAME è il nome codificato tramite URL che vuoi utilizzare. Ad esempio, pets/cat.png, codificato come URL pets%2Fcat.png.

Passaggi successivi