刪除物件

本頁面說明如何從 Cloud Storage 的值區刪除物件

必要的角色

如要取得刪除物件所需的權限,請要求管理員為您授予儲存空間物件使用者 (roles/storage.objectUser) IAM 角色,適用於包含您要刪除物件的值區。

如果您打算使用 Google Cloud 控制台完成本頁面的任務,請請管理員授予您 Storage 管理員 (roles/storage.admin) 角色,而非 Storage 物件使用者 (roles/storage.objectUser) 角色,或是除了 Storage 物件使用者 (roles/storage.objectUser) 角色之外,還授予 Viewer (roles/viewer) 基本角色。

這些角色包含刪除物件所需的權限。如要查看所需的確切權限,請展開「必要權限」部分:

所需權限

  • storage.objects.delete
  • storage.objects.list
    • 只有在使用 Google Cloud 主控台,或在 Google Cloud CLI 中使用 --recursive 標記或萬用字元時,才需要這項權限。
  • storage.buckets.list
    • 只有在使用 Google Cloud 控制台執行本頁操作說明時,才需要這項權限。

您也可以透過其他預先定義的角色自訂角色取得這些權限。

如要進一步瞭解如何授予值區角色,請參閱「在值區中使用 IAM」。

刪除物件

如要從一個 Cloud Storage 值區刪除物件,請完成下列步驟:

控制台

  1. 在 Google Cloud 控制台,前往 Cloud Storage「Buckets」頁面。

    前往「Buckets」(值區) 頁面

  2. 在值區清單中,按一下包含要刪除物件的值區名稱。

    「Bucket details」頁面隨即開啟,並選取「Objects」分頁標籤。

  3. 前往可能位於資料夾中的物件。

  4. 找出要刪除的每個物件,然後勾選旁邊的核取方塊。

    您也可以按一下資料夾的核取方塊,刪除該資料夾中包含的所有物件。

  5. 按一下 [Delete] (刪除) 按鈕。

  6. 在隨即出現的對話方塊中按一下 [Delete] (刪除)

如果您一次刪除多個物件,可以按一下 Google Cloud 控制台中的「通知」圖示,追蹤刪除進度。Google Cloud 主控台可大量刪除多達數百萬個物件,且會在背景執行。

如要瞭解如何在 Google Cloud 控制台中取得 Cloud Storage 作業失敗的詳細錯誤資訊,請參閱疑難排解

指令列

使用 Google Cloud CLI 指令 gcloud storage rm

gcloud storage rm gs://BUCKET_NAME/OBJECT_NAME

其中:

  • BUCKET_NAME 是包含要刪除物件的值區名稱。例如:my-bucket
  • OBJECT_NAME 是要刪除的物件名稱。例如:pets/dog.png

如果成功,回應會類似以下範例:

Removing objects:
Removing gs://example-bucket/file.txt...
  Completed 1/1

用戶端程式庫

C++

詳情請參閱 Cloud Storage C++ API 參考說明文件

如要驗證 Cloud Storage,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

namespace gcs = ::google::cloud::storage;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& object_name) {
  google::cloud::Status status =
      client.DeleteObject(bucket_name, object_name);

  if (!status.ok()) throw std::runtime_error(status.message());
  std::cout << "Deleted " << object_name << " in bucket " << bucket_name
            << "\n";
}

C#

詳情請參閱 Cloud Storage C# API 參考說明文件

如要驗證 Cloud Storage,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。


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

public class DeleteFileSample
{
    public void DeleteFile(
        string bucketName = "your-unique-bucket-name",
        string objectName = "your-object-name")
    {
        var storage = StorageClient.Create();
        storage.DeleteObject(bucketName, objectName);
        Console.WriteLine($"Deleted {objectName}.");
    }
}

Go

詳情請參閱 Cloud Storage Go API 參考說明文件

如要驗證 Cloud Storage,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

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

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

// deleteFile removes specified object.
func deleteFile(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()

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

	// Optional: set a generation-match precondition to avoid potential race
	// conditions and data corruptions. The request to delete the file is aborted
	// if the object's generation number does not match your precondition.
	attrs, err := o.Attrs(ctx)
	if err != nil {
		return fmt.Errorf("object.Attrs: %w", err)
	}
	o = o.If(storage.Conditions{GenerationMatch: attrs.Generation})

	if err := o.Delete(ctx); err != nil {
		return fmt.Errorf("Object(%q).Delete: %w", object, err)
	}
	fmt.Fprintf(w, "Blob %v deleted.\n", object)
	return nil
}

Java

詳情請參閱 Cloud Storage Java API 參考說明文件

如要驗證 Cloud Storage,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

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 DeleteObject {
  public static void deleteObject(String projectId, String bucketName, String objectName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

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

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Blob blob = storage.get(bucketName, objectName);
    if (blob == null) {
      System.out.println("The object " + objectName + " wasn't found in " + bucketName);
      return;
    }
    BlobId idWithGeneration = blob.getBlobId();
    // Deletes the blob specified by its id. When the generation is present and non-null it will be
    // specified in the request.
    // If versioning is enabled on the bucket and the generation is present in the delete request,
    // only the version of the object with the matching generation will be deleted.
    // If instead you want to delete the current version, the generation should be dropped by
    // performing the following.
    // BlobId idWithoutGeneration =
    //    BlobId.of(idWithGeneration.getBucket(), idWithGeneration.getName());
    // storage.delete(idWithoutGeneration);
    storage.delete(idWithGeneration);

    System.out.println("Object " + objectName + " was permanently deleted from " + bucketName);
  }
}

Node.js

詳情請參閱 Cloud Storage Node.js API 參考說明文件

如要驗證 Cloud Storage,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

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

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

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

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

// Optional:
// Set a generation-match precondition to avoid potential race conditions
// and data corruptions. The request to delete 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 deleteOptions = {
  ifGenerationMatch: generationMatchPrecondition,
};
async function deleteFile() {
  await storage.bucket(bucketName).file(fileName).delete(deleteOptions);

  console.log(`gs://${bucketName}/${fileName} deleted`);
}

deleteFile().catch(console.error);

PHP

詳情請參閱 Cloud Storage PHP API 參考說明文件

如要驗證 Cloud Storage,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

use Google\Cloud\Storage\StorageClient;

/**
 * Delete an object.
 *
 * @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')
 */
function delete_object(string $bucketName, string $objectName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $object->delete();
    printf('Deleted gs://%s/%s' . PHP_EOL, $bucketName, $objectName);
}

Python

詳情請參閱 Cloud Storage Python API 參考說明文件

如要驗證 Cloud Storage,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

from google.cloud import storage


def delete_blob(bucket_name, blob_name):
    """Deletes a blob from the bucket."""
    # bucket_name = "your-bucket-name"
    # blob_name = "your-object-name"

    storage_client = storage.Client()

    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(blob_name)
    generation_match_precondition = None

    # Optional: set a generation-match precondition to avoid potential race conditions
    # and data corruptions. The request to delete is aborted if the object's
    # generation number does not match your precondition.
    blob.reload()  # Fetch blob metadata to use in generation_match_precondition.
    generation_match_precondition = blob.generation

    blob.delete(if_generation_match=generation_match_precondition)

    print(f"Blob {blob_name} deleted.")

Ruby

詳情請參閱 Cloud Storage Ruby API 參考說明文件

如要驗證 Cloud Storage,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

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

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

  require "google/cloud/storage"

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

  file.delete

  puts "Deleted #{file.name}"
end

REST API

JSON API

  1. 安裝並初始化 gcloud CLI,這樣您就能為 Authorization 標頭產生存取權杖。

  2. 使用 cURL 透過 DELETE 要求呼叫 JSON API

    curl -X DELETE \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/o/OBJECT_NAME"

    其中:

    • BUCKET_NAME 是包含要刪除物件的值區名稱。例如:my-bucket
    • OBJECT_NAME 是您要刪除的物件以網址編碼的名稱。例如 pets/dog.png,網址編碼為 pets%2Fdog.png

XML API

  1. 安裝並初始化 gcloud CLI,這樣您就能為 Authorization 標頭產生存取權杖。

  2. 使用 cURL 透過 DELETE Object 要求呼叫 XML API

    curl -X DELETE \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      "https://storage.googleapis.com/BUCKET_NAME/OBJECT_NAME"

    其中:

    • BUCKET_NAME 是包含要刪除物件的值區名稱。例如:my-bucket
    • OBJECT_NAME 是您要刪除的物件以網址編碼的名稱。例如 pets/dog.png,網址編碼為 pets%2Fdog.png

大量刪除物件

如果要大量刪除十萬個以上的物件,請避免使用 gcloud storage,因為這項程序需要很長的時間才能完成。請改用下列任一做法:

  • 物件生命週期管理功能可刪除任意數量的物件。如要使用這項功能大量刪除值區中的物件,請在值區上設定生命週期設定規則,其中條件中的 Age 設為 0 天,而動作設為 delete。設定規則後,Cloud Storage 會以非同步方式執行大量刪除作業

  • 刪除最多一百萬個物件時,建議您使用 Google Cloud 主控台。提出這類刪除要求後,系統會在背景執行這項作業。如要查看批次刪除作業的狀態,請按一下 Google Cloud 主控台標題中的「通知」按鈕 ()。

  • 使用特定用戶端程式庫或直接使用 JSON API 時,您可以批次刪除要求,以減少需要建立的 HTTP 連線數量。

後續步驟