העתקה, שינוי שם והעברה של אובייקטים

בדף הזה מוסבר איך להעתיק אובייקטים, לשנות את השם שלהם ולהעביר אותם. בכלים מסוימים מתבצעות פעולות אטומיות של העברת אובייקטים, ובכלים אחרים מתבצעת סימולציה של פעולת העברת אובייקט על ידי העתקת האובייקט למיקום חדש שצוין, ואז מחיקת האובייקט המקורי.

לפני שמתחילים

כדי להעתיק, לשנות את השם או להעביר אובייקטים, צריך לקבל את תפקידי ה-IAM הנדרשים. בקטעים הבאים מתוארות דרישות IAM לתרחישים שונים לדוגמה.

העתקת אובייקטים (כולל העברה או שינוי שם באמצעות העתקה)

כדי לקבל את ההרשאות שדרושות להעתקת אובייקטים, בקשו מהאדמין להקצות לכם את תפקידי ה-IAM הבאים בקטגוריית המקור שמכילה את האובייקטים שאתם רוצים להעביר, או בקטגוריית היעד שאליה אתם רוצים להעביר את האובייקטים:

  • צפייה באובייקטים של אחסון (roles/storage.objectViewer) בקטגוריית המקור
  • ‫Storage Object User‏ (roles/storage.objectUser) בקטגוריית היעד
  • כדי להעתיק אובייקטים באמצעות מסוף Cloud de Confiance : התפקיד הבסיסי "צפייה" (roles/viewer) בקטגוריית המקור ובקטגוריית היעד, בנוסף להרשאות roles/storage.objectViewer ו-roles/storage.objectUser

התפקידים המוגדרים מראש האלה כוללים את ההרשאות שנדרשות להעתקת אובייקטים. כדי לראות בדיוק אילו הרשאות נדרשות, אפשר להרחיב את הקטע ההרשאות הנדרשות:

ההרשאות הנדרשות

כדי להעתיק אובייקטים, צריך את ההרשאות הבאות:

  • ‫storage.objects.get בקטגוריית המקור
  • ‫storage.objects.create בקטגוריית היעד
  • ‫storage.objects.delete (נדרש רק אם מחליפים או משכתבים אובייקט בקטגוריית היעד כחלק מפעולת העתקה או העברה של אובייקט) בקטגוריית היעד
  • ‫storage.objects.delete (נדרשת רק אם מעבירים אובייקט באמצעות פעולת העתקה ומחיקה בסיסית) בקטגוריית המקור
  • ‫storage.folders.create (נדרש רק אם האובייקט שמעבירים נמצא בתיקייה שרוצים ליצור בקטגוריית היעד) בקטגוריית היעד
  • ‫storage.objects.list (נדרשת רק אם מעתיקים, מעבירים או משנים את השם של אובייקט באמצעות מסוף Cloud de Confiance ) בקטגוריות המקור והיעד
  • ‫storage.buckets.list (נדרשת רק אם מעתיקים, מעבירים או משנים שם של אובייקט באמצעות מסוף Cloud de Confiance ) בפרויקט שמכיל את קטגוריות המקור והיעד

אפשר לקבל את ההרשאות האלה גם באמצעות תפקידים בהתאמה אישית.

במאמר הגדרה וניהול של מדיניות IAM בקטגוריות מוסבר איך מקצים תפקידים בקטגוריות. במאמר ניהול הגישה לפרויקטים מוסבר איך מקצים תפקידים בפרויקטים.

אם באובייקט שרוצים להעתיק מופעלות תכונות מסוימות, יכול להיות שתצטרכו תפקידים נוספים או חלופיים. לדוגמה, אם לאובייקט שרוצים להעתיק יש הגדרת שמירה שרוצים לשמור, צריך תפקיד בקטגוריית היעד שכולל את ההרשאה storage.objects.setRetention, כמו התפקיד Storage Object Admin‏ (roles/storage.objectAdmin). מידע נוסף זמין במאמר הרשאות IAM ל-Cloud Storage.

שינוי שמות של אובייקטים באופן אטומי

כדי לקבל את ההרשאות שדרושות לשינוי שם של אובייקטים באופן אטומי, בקשו מהאדמין לתת לכם את התפקיד משתמש באובייקטים של אחסון (roles/storage.objectUser) ב-IAM בקטגוריה שמכילה את האובייקט שאתם רוצים לשנות את השם שלו.

זהו תפקיד שמוגדר מראש וכולל את ההרשאות שנדרשות לשינוי שמות של אובייקטים באופן אטומי. כדי לראות בדיוק אילו הרשאות נדרשות, אפשר להרחיב את הקטע ההרשאות הנדרשות:

ההרשאות הנדרשות

כדי לשנות שמות של אובייקטים באופן אטומי, נדרשות ההרשאות הבאות:

  • storage.objects.move
  • storage.objects.create
  • ‫storage.objects.delete (נדרש רק אם מחליפים אובייקט)

אפשר לקבל את ההרשאות האלה גם באמצעות תפקידים בהתאמה אישית.

במאמר הגדרה וניהול של מדיניות IAM בקטגוריות מוסבר איך מקצים תפקידים בקטגוריות.

העתקת אובייקטים

בקטע הזה מוסבר איך להעתיק אובייקטים. אפשר להעתיק אובייקטים מקטגוריה אחת לאחרת.

המסוף

  1. במסוף Cloud de Confiance , נכנסים לדף Buckets של Cloud Storage.

    כניסה לדף Buckets

  2. ברשימת הקטגוריות, לוחצים על שם הקטגוריה שמכילה את האובייקט שרוצים להעתיק.

    הדף Bucket details נפתח עם הכרטיסייה Objects שנבחרה.

  3. עוברים אל האובייקט, שאולי יהיה ממוקם בתיקייה.

  4. לוחצים על התפריט Object overflow () שמשויך לאובייקט.

  5. לוחצים על Copy.

    מופיעה החלונית Copy object.

  6. בשדה Destination, מקלידים את השם של קטגוריית היעד ואת השם לאובייקט שמעתיקים.

    אפשר גם ללחוץ על Browse כדי לבחור את היעד, אבל אפשרויות הבחירה מוגבלות לקטגוריות בפרויקט הנוכחי.

  7. לוחצים על Copy.

במאמר פתרון בעיות מוסבר איך מקבלים מידע מפורט על שגיאות בנושא פעולות ב-Cloud Storage שנכשלו במסוף Cloud de Confiance .

שורת הפקודה

משתמשים בפקודה gcloud storage cp:

gcloud storage 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.

אם הפעולה בוצעה ללא שגיאות, התשובה תיראה כמו בדוגמה הבאה:

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

ספריות לקוח

C++

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage C++ API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

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#

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage C# API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.


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

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Go API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

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

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Java API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.


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

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Node.js API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

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

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage PHP API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

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

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Python API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

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

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Ruby API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

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

Rust

use google_cloud_storage::builder_ext::RewriteObjectExt;
use google_cloud_storage::client::StorageControl;

pub async fn sample(
    client: &StorageControl,
    source_bucket_id: &str,
    dest_bucket_id: &str,
) -> anyhow::Result<()> {
    const SOURCE_NAME: &str = "object-to-copy";
    const DEST_NAME: &str = "copied-object";
    let copied = client
        .rewrite_object()
        .set_source_bucket(format!("projects/_/buckets/{source_bucket_id}"))
        .set_source_object(SOURCE_NAME)
        .set_destination_bucket(format!("projects/_/buckets/{dest_bucket_id}"))
        .set_destination_name(DEST_NAME)
        .rewrite_until_done()
        .await?;
    println!(
        "successfully copied {source_bucket_id}/{SOURCE_NAME} to {dest_bucket_id}/{DEST_NAME}: {copied:?}"
    );
    Ok(())
}

ממשקי API בארכיטקטורת REST

‫API בפורמט JSON

  1. להתקין ולהפעיל את ה-CLI של gcloud, כדי שתוכלו ליצור אסימון גישה לכותרת Authorization.

  2. משתמשים ב-cURL כדי לשלוח קריאה ל-API בפורמט JSON באמצעות בקשה של אובייקט POST:

    curl -X POST \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Length: 0" \
      "https://storage.s3nsapis.fr/storage/v1/b/SOURCE_BUCKET_NAME/o/SOURCE_OBJECT_NAME/rewriteTo/b/DESTINATION_BUCKET_NAME/o/NAME_OF_COPY"

    כאשר:

    • ‫SOURCE_BUCKET_NAME הוא שם הקטגוריה שמכילה את האובייקט שרוצים להעתיק. לדוגמה, my-bucket.
    • ‫SOURCE_OBJECT_NAME הוא השם של האובייקט שרוצים להעתיק, בקידודי תווים שמתאימים לכתובת URL. לדוגמה, pets/dog.png יותאם לקידודי התווים שמתאימים לכתובות URL באופן הבא: pets%2Fdog.png.
    • ‫DESTINATION_BUCKET_NAME הוא שם הקטגוריה שאליה רוצים להעתיק את האובייקט. לדוגמה, another-bucket.
    • ‫NAME_OF_COPY הוא השם שרוצים לתת לעותק של האובייקט, בקידודי תווים שמתאימים ל-URL. לדוגמה, shiba.png.

    מכיוון ששיטת rewrite מעתיקה נתונים במקטעים בגודל מוגבל, ייתכן שיהיה צורך ליצור כמה בקשות העתקה, במיוחד לאובייקטים גדולים.

    לדוגמה, התגובה הבאה לבקשת rewrite מראה שצריך לשלוח בקשות rewrite נוספות:

    {
      "kind": "storage#rewriteResponse",
      "totalBytesRewritten": 1048576,
      "objectSize": 10000000000,
      "done": false,
      "rewriteToken": TOKEN_VALUE
    }
  3. בבקשה הבאה משתמשים ב-rewriteToken כדי להמשיך בהעתקת הנתונים:

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

    כאשר:

    • ‫TOKEN_VALUE הוא הערך של rewriteToken שהוחזר בבקשה הקודמת.
    • כל שאר הערכים תואמים לאלה ששימשו בבקשה הקודמת.

    כשמעתיקים את האובייקט במלואו, בתגובה האחרונה המאפיין (property) done מוגדר כ-true, אין מאפיין rewriteToken והמטא-נתונים של העותק נכללים במאפיין resource.

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

‫API בפורמט XML

  1. להתקין ולהפעיל את ה-CLI של gcloud, כדי שתוכלו ליצור אסימון גישה לכותרת Authorization.

  2. משתמשים ב-cURL כדי לשלוח קריאה ל-API בפורמט XML באמצעות בקשה של אובייקט PUT:

    curl -X PUT \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "x-goog-copy-source: SOURCE_BUCKET_NAME/SOURCE_OBJECT_NAME" \
      "https://storage.s3nsapis.fr/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 הוא השם שרוצים לתת לעותק של האובייקט, בקידודי תווים שמתאימים ל-URL. לדוגמה, shiba.png.

העברה או שינוי שם של אובייקטים באמצעות העתקה

כאן מוסבר איך להעביר אובייקטים או לשנות את השם שלהם באמצעות פעולות בסיסיות של העתקת אובייקטים. הכלים שמתוארים בקטע הזה מעבירים אובייקטים ומשנים את השמות שלהם על ידי העתקת האובייקט המקורי למרחב שמות אחר, ואז מחיקת האובייקט המקורי.

המסוף

  1. במסוף Cloud de Confiance , נכנסים לדף Buckets של Cloud Storage.

    כניסה לדף Buckets

  2. ברשימת הקטגוריות, לוחצים על שם הקטגוריה שמכילה את האובייקט שרוצים להעביר.

    הדף Bucket details נפתח עם הכרטיסייה Objects שנבחרה.

  3. עוברים אל האובייקט, שאולי יהיה ממוקם בתיקייה.

  4. לוחצים על התפריט Object overflow () שמשויך לאובייקט.

  5. אם רוצים לתת לאובייקט שם חדש באותה קטגוריה, לוחצים על Rename.

    1. בחלון שכבת-העל שמופיע, מזינים שם חדש לאובייקט.

    2. לוחצים על Rename.

  6. אם רוצים להעביר את האובייקט לקטגוריה אחרת, לוחצים על Move.

    1. בחלון שכבת-העל שמופיע, לוחצים על Browse.

    2. בוחרים את היעד לאובייקט שרוצים להעביר.

    3. לוחצים על Select.

    4. לוחצים על Move.

במאמר פתרון בעיות מוסבר איך מקבלים מידע מפורט על שגיאות בנושא פעולות ב-Cloud Storage שנכשלו במסוף Cloud de Confiance .

שורת הפקודה

משתמשים בפקודה gcloud storage mv:

gcloud storage 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.

אם הפעולה בוצעה ללא שגיאות, התשובה תיראה כמו בדוגמה הבאה:

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 

ספריות לקוח

C++

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage C++ API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

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#

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage C# API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.


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

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Go API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

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

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Java API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.


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

public class CopyDeleteObject {
  public static void copyDeleteObject(
      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 sourceBucketName = "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;
    BlobInfo existingTarget = storage.get(targetBucketName, targetObjectName);
    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());
    }

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

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Node.js API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

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

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage PHP API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

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

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Python API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

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

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Ruby API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

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

Rust

use google_cloud_storage::builder_ext::RewriteObjectExt;
use google_cloud_storage::client::StorageControl;

pub async fn sample(
    client: &StorageControl,
    source_bucket_id: &str,
    dest_bucket_id: &str,
) -> anyhow::Result<()> {
    const SOURCE_NAME: &str = "object-to-move";
    const DEST_NAME: &str = "moved-object";
    let moved = client
        .rewrite_object()
        .set_source_bucket(format!("projects/_/buckets/{source_bucket_id}"))
        .set_source_object(SOURCE_NAME)
        .set_destination_bucket(format!("projects/_/buckets/{dest_bucket_id}"))
        .set_destination_name(DEST_NAME)
        .rewrite_until_done()
        .await?;

    client
        .delete_object()
        .set_bucket(format!("projects/_/buckets/{source_bucket_id}"))
        .set_object(SOURCE_NAME)
        .send()
        .await?;
    println!(
        "successfully moved {source_bucket_id}/{SOURCE_NAME} to {dest_bucket_id}/{DEST_NAME}: {moved:?}"
    );

    Ok(())
}

ממשקי API בארכיטקטורת REST

‫API בפורמט JSON

הוראות להעברה או לשינוי שם של אובייקטים באמצעות העתקה ב-API בפורמט JSON מופיעות במאמר העתקת אובייקטים.

‫API בפורמט XML

במאמר העתקת אובייקטים מוסבר איך להעביר אובייקטים או לשנות את השם שלהם באמצעות העתקה ב-API בפורמט XML.

שינוי שמות של אובייקטים באופן אטומי

בקטע הזה מוסבר איך לשנות שמות של אובייקטים בקטגוריה באופן אטומי. כדי לשנות שם של אובייקט, אפשר להשתמש ב-method‏ Objects: move ב-API בפורמט JSON של Cloud Storage.

ממשקי API בארכיטקטורת REST

‫API בפורמט JSON

  1. להתקין ולהפעיל את ה-CLI של gcloud, כדי שתוכלו ליצור אסימון גישה לכותרת Authorization.

  2. משתמשים ב-cURL כדי לשלוח קריאה ל-API בפורמט JSON באמצעות בקשת Objects: move:

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

    כאשר:

    • ‫BUCKET_NAME הוא שם הקטגוריה שמכילה את האובייקט שרוצים לשנות את השם שלו. לדוגמה, my-bucket.
    • ‫SOURCE_OBJECT_NAME הוא השם של האובייקט שרוצים לשנות, בקידודי תווים שמתאימים לכתובת URL. לדוגמה, pets/dog.png יותאם לקידודי התווים שמתאימים לכתובות URL באופן הבא: pets%2Fdog.png.
    • ‫DESTINATION_OBJECT_NAME הוא השם שרוצים להשתמש בו, בקידודי תווים שמתאימים לכתובות URL. לדוגמה, pets/cat.png יותאם לקידודי התווים שמתאימים לכתובות URL באופן הבא: pets%2Fcat.png.

המאמרים הבאים