删除对象

本页面介绍了如何从 Cloud Storage 中的存储桶删除对象

准备工作

如需获得删除对象所需的权限,请让您的管理员向您授予包含待删除对象的存储桶的 Storage Object User (roles/storage.objectUser) IAM 角色。

如果您打算使用 Google Cloud 控制台完成本页面上的任务,请让您的管理员授予您 Storage Admin (roles/storage.admin) 角色,而不是 Storage Object User (roles/storage.objectUser) 角色;或者在授予 Storage Object User (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 存储桶页面。

    进入“存储桶”

  2. 在存储桶列表中,点击包含待删除对象的存储桶的名称。

    此时会打开“存储桶详情”页面,其中“对象”标签页已选中。

  3. 导航到可能位于文件夹中的对象。

  4. 点击要删除的每个对象对应的复选框。

    您还可以点击文件夹对应的复选框,这将删除该文件夹中包含的所有对象。

  5. 点击删除按钮。

  6. 在出现的对话框中点击删除

如果您一次性删除许多对象,则可以点击 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.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;
    }

    // Optional: set a generation-match precondition to avoid potential race
    // conditions and data corruptions. The request to upload returns a 412 error if
    // the object's generation number does not match your precondition.
    Storage.BlobSourceOption precondition =
        Storage.BlobSourceOption.generationMatch(blob.getGeneration());

    storage.delete(bucketName, objectName, precondition);

    System.out.println("Object " + objectName + " was 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. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。如需了解相关说明,请参阅 API 身份验证
  2. 使用 cURL,通过 DELETE 请求调用 JSON API

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

    其中:

    • OAUTH2_TOKEN 是您在第 1 步中生成的访问令牌的名称。
    • BUCKET_NAME 是包含待删除对象的存储桶的名称,例如 my-bucket
    • OBJECT_NAME 是要删除的对象的网址编码名称。例如,pets/dog.png 的网址编码为 pets%2Fdog.png

XML API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。如需了解相关说明,请参阅 API 身份验证
  2. 使用 cURL,通过 DELETE Object 请求调用 XML API

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

    其中:

    • OAUTH2_TOKEN 是您在第 1 步中生成的访问令牌的名称。
    • 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 连接数量。

后续步骤