刪除物件

本頁面說明如何從 Cloud Storage 的值區刪除物件。如要瞭解物件刪除方法,請參閱「關於物件刪除」。

必要的角色

如要取得刪除物件所需的權限,請要求管理員在包含要刪除物件的 bucket 中,授予您下列 IAM 角色:

  • 使用 Google Cloud CLI 或 REST API 刪除物件: Storage Object User (roles/storage.objectUser)
  • 使用 Google Cloud 控制台刪除物件: Storage 管理員 (roles/storage.admin)
  • 如要使用 Google Cloud 控制台刪除物件,請按照下列步驟操作: 檢視者 (roles/viewer) 和 Storage 物件使用者 (roles/storage.objectUser)

如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和組織的存取權」。

這些預先定義的角色具備刪除物件所需的權限。如要查看確切的必要權限,請展開「Required permissions」(必要權限) 部分:

所需權限

如要刪除物件,您必須具備下列權限:

  • 刪除物件: storage.objects.delete
  • 使用 Google Cloud 控制台列出物件,或在 Google Cloud CLI 中使用 --recursive 旗標或萬用字元: storage.objects.list
  • 使用 Google Cloud 控制台列出 bucket: storage.buckets.list

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

刪除單一物件

本節說明如何一次刪除一個物件。

如要刪除單一物件,請完成下列步驟:

控制台

  1. 前往 Google Cloud 控制台的「Cloud Storage bucket」頁面。

    前往「Buckets」(值區) 頁面

  2. 在 bucket 清單中,點選含有要刪除物件的 bucket 名稱。

    系統會開啟「Bucket details」(值區詳細資料) 頁面,並選取「Objects」(物件) 分頁標籤。

  3. 前往該物件 (可能位於資料夾中)。

  4. 選取要刪除的物件旁的核取方塊。

  5. 按一下「刪除」,然後在隨即顯示的對話方塊中按一下「刪除」

指令列

使用 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

Rust

use google_cloud_storage::client::StorageControl;

pub async fn sample(client: &StorageControl, bucket_id: &str) -> anyhow::Result<()> {
    const NAME: &str = "deleted-object-name";
    client
        .delete_object()
        .set_bucket(format!("projects/_/buckets/{bucket_id}"))
        .set_object(NAME)
        // Consider .set_generation() to make request idempotent
        .send()
        .await?;
    println!("successfully deleted object {NAME} in bucket {bucket_id}");
    Ok(())
}

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

大量刪除物件

本節說明如何透過在Google Cloud 主控台中選取物件、使用指令列工具刪除具有相同前置字元的物件,或在 API 或用戶端程式庫要求中指定物件清單,來大量刪除物件。

控制台

  1. 前往 Google Cloud 控制台的「Cloud Storage bucket」頁面。

    前往「Buckets」(值區) 頁面

  2. 在 bucket 清單中,點選含有要刪除物件的 bucket 名稱。

    系統會開啟「Bucket details」(值區詳細資料) 頁面,並選取「Objects」(物件) 分頁標籤。

  3. 前往該物件 (可能位於資料夾中)。

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

    選取資料夾的核取方塊,即可刪除該資料夾內的所有物件。

  5. 按一下「刪除」,然後在隨即顯示的對話方塊中按一下「刪除」

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

如要瞭解如何透過 Google Cloud 控制台取得 Cloud Storage 作業失敗的詳細錯誤資訊,請參閱「疑難排解」一文。

指令列

Google Cloud CLI

如要刪除具有相同前置字串的一組物件 (例如名稱模仿資料夾結構的物件),請搭配使用 gcloud storage rm 旗標和 --recursive 旗標

gcloud storage rm --recursive gs://BUCKET_NAME/PREFIX

其中:

  • BUCKET_NAME 是值區名稱。例如:my-bucket
  • PREFIX 是要刪除之物件的共同前置字串。例如:pets/

Amazon S3 CLI

如要使用 Amazon S3 CLI 刪除 Cloud Storage 中的多個物件,請使用 aws s3api delete-objects 指令。您需要將要求重新導向至 Cloud Storage 多個物件刪除 XML API,方法是將 --endpoint-url 標記設為 storage.googleapis.com。如要瞭解 delete-objects API 的詳細參數定義和行為,請參閱 Amazon S3 CLI delete-objects 參考文件

用戶端程式庫

Cloud Storage 透過 Amazon S3 相容介面支援多個物件刪除 XML API。如要使用與 Amazon S3 相容的用戶端程式庫大量刪除物件,請在用戶端設定中將端點網址設為 https://storage.googleapis.com,將要求指向 Google Cloud 端點。如果您要執行下列任一工作,這個方法會很有幫助:

  • 運用現有的程式碼集或已為 Amazon S3 建構的工具。
  • 在包含 Amazon S3 和 Cloud Storage 的多雲端環境中,維持一致性。

以下範例說明如何使用 Boto3 程式庫初始化用戶端,以便與 Cloud Storage 互動:

  import boto3
  def main():
  # Initialize the S3 client to point to the Google Cloud Storage endpoint
    client = boto3.client(
        service_name='s3',
        endpoint_url='https://storage.googleapis.com',
        aws_access_key_id='YOUR_ACCESS_ID',
        aws_secret_access_key='YOUR_SECRET',
    )
  # Perform delete operations as defined in the library's documentation
  # response = client.delete_objects(Bucket='BUCKET_NAME', Delete={'Objects': [...]})
  

如需特定方法簽章和參數定義,請參閱 delete_objects Boto3 說明文件

XML API

如要使用 XML API,在單一要求中刪除最多 1,000 個物件,請完成下列步驟:

  1. 安裝並初始化gcloud CLI,以便為 Authorization 標頭產生存取權杖。

  2. 建立 XML 文件,指定要刪除的物件。

    如需完整設定清單,請參閱 XML API 參考文件中的「 刪除多個物件」。XML 檔案中要加入的常見設定如下:

    <Delete>
        <Object>
          <Key>OBJECT_NAME</Key>
          <VersionId>VERSION_ID</VersionId>
        </Object>
        ...
        <Quiet>QUIET_RESPONSE_BOOLEAN</Quiet>
      </Delete>

    其中:

    • OBJECT_NAME 是物件的網址編碼名稱。例如 pets/dog.png,網址編碼為 pets%2Fdog.png。您最多可以在 XML 檔案中指定 1,000 個物件。
    • VERSION_ID 是物件的版本 ID。例如:11111
    • QUIET_RESPONSE_BOOLEAN 可控制 API 回應的詳細程度:
      • 如要取得詳細回應,請設為 False。無論物件是否成功刪除,回應都會包含每個物件的詳細資料。使用 XML API 執行的多重物件刪除作業並非不可分割。如果要求導致部分失敗,系統可能會成功刪除某些物件,但其他物件可能無法刪除,因此建議使用詳細回應來識別所有物件刪除作業。如果已啟用資料存取稽核記錄,您也可以查看稽核記錄,瞭解失敗的詳細資料。
      • 如要讓語音助理以較小的音量回應,請將這個屬性的值設為 True。回應主體不會包含成功刪除的物件相關資訊。
  3. 使用 curlPOST bucket 要求傳送至 XML API,並附上 ?delete 查詢參數和 XML 檔案:

    curl -X POST --data-binary @XML_FILE_NAME \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      "https://storage.googleapis.com/BUCKET_NAME?delete"

    其中:

    • XML_FILE_NAME 是您建立的 XML 檔案名稱。
    • BUCKET_NAME 是包含要刪除物件的值區名稱。

      如果停用 Quiet 模式,詳細回應可能如下所示:

      <DeleteResult>
      <Deleted>
        <Key>images/photo1.jpg</Key>
        <VersionId>11111</VersionId>
      </Deleted>
      <Deleted>
        <Key>documents/report.pdf</Key>
        <VersionId>22222</VersionId>
      </Deleted>
      <Error>
        <Code>AccessDenied</Code>
        <Key>private/financial_data.xlsx</Key>
        <Message>Access Denied. You don't have permission to delete this object.</Message>
        <VersionId>33333</VersionId>
      </Error>
      </DeleteResult>
      

      如果啟用 Quiet 模式,回應只會列出刪除失敗的物件。如果所有物件都已成功刪除,系統會傳回空白的 <DeleteResult/> 標記。以下是發生錯誤時的無聲回應範例:

      <DeleteResult>
      <Error>
        <Code>AccessDenied</Code>
        <Key>private/financial_data.xlsx</Key>
        <Message>Access Denied. You don't have permission to delete this object.</Message>
        <VersionId>33333</VersionId>
      </Error>
      </DeleteResult>

刪除最多數十億個物件

如要透過單一物件刪除作業刪除數百萬或數十億個物件,請使用儲存空間批次作業。如要建立工作,請指定要刪除的物件,方法是在資訊清單檔案中提供物件清單,或使用物件前置字串。指定物件清單後,請建立批次作業工作來刪除物件

使用物件生命週期規則自動刪除物件

如要讓系統在物件符合您指定的條件 (例如存在時間或儲存空間級別) 時自動刪除物件,請使用物件生命週期管理。舉例來說,您可以設定生命週期規則,刪除超過 30 天的記錄。

使用 JSON API 批次刪除物件要求

如要使用 JSON API 刪除大量物件,並減少所需的 HTTP 連線數量,請使用 JSON API 批次要求。您最多可將 100 個 API 呼叫分組為單一 HTTP 要求,有助於減少網路負擔。

後續步驟