Tous les produits
Search
Centre de documentation

Object Storage Service:Delete objects (OSS SDK for Go 1.0)

Dernière mise à jour :Sep 22, 2026

Supprimez un objet unique, plusieurs objets par nom, les objets correspondant à un préfixe ou un répertoire entier.

Avertissement

La suppression d'objets est irréversible. Procédez avec prudence.

Notes

  • Cette rubrique utilise le point de terminaison public de la région Chine (Hangzhou). Si vous souhaitez accéder à OSS depuis d'autres services Alibaba Cloud situés dans la même région, utilisez un point de terminaison interne. Pour plus d'informations sur les régions et les points de terminaison OSS, consultez Régions et points de terminaison.

  • Dans cette rubrique, les identifiants d'accès sont obtenus à partir des variables d'environnement. Pour savoir comment configurer les identifiants d'accès, consultez Configurer les identifiants d'accès.

  • Cette rubrique montre comment créer une instance OSSClient avec un endpoint OSS. Pour d'autres configurations, telles que l'utilisation d'un domaine personnalisé ou l'authentification via des identifiants du Security Token Service (STS), consultez Configurer un client (Go SDK V1).

  • Pour supprimer un objet, vous devez disposer de l'autorisation oss:DeleteObject. Pour plus d'informations, consultez Accorder une politique personnalisée.

Supprimer un objet unique

Le code suivant supprime un objet nommé exampleobject.txt d'un bucket nommé examplebucket :

package main

import (
	"log"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance. 
	// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
	// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify the actual region.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Specify the version of the signature algorithm.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the name of the bucket. Example: examplebucket. 
	bucketName := "examplebucket"
	// Set objectName to the full path of the object that you want to delete. The full path must contain the extension of the object name but cannot contain the bucket name. Example: exampledir/exampleobject.txt. 
	// If you want to delete a directory, set objectName to the directory name. If the directory contains objects, you must delete all objects from the directory before you can delete the directory. 
	objectName := "exampledir/exampleobject.txt"

	// Create a bucket.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket '%s': %v", bucketName, err)
	}

	// Delete the object. 
	err = bucket.DeleteObject(objectName)
	if err != nil {
		log.Fatalf("Failed to delete object '%s': %v", objectName, err)
	}

	log.Printf("Successfully deleted object: %s\n", objectName)
}

Supprimer plusieurs objets

Vous pouvez supprimer jusqu'à 1 000 objets à la fois par nom, par préfixe ou par répertoire.

Vous pouvez également configurer des règles de cycle de vie pour supprimer automatiquement les objets. Pour plus d'informations, consultez Règles de cycle de vie basées sur la dernière heure de modification.

Supprimer des objets par nom

Exemple de code pour supprimer plusieurs objets par nom :

package main

import (
	"log"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance. 
	// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
	// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify the actual region.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Specify the version of the signature algorithm.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the name of the bucket. Example: examplebucket. 
	bucketName := "examplebucket"

	// Create a bucket.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket '%s': %v", bucketName, err)
	}

	// Delete multiple objects and the result is returned.
	objectsToDelete := []string{"my-object-1", "my-object-2"}
	delRes, err := bucket.DeleteObjects(objectsToDelete)
	if err != nil {
		log.Fatalf("Failed to delete objects: %v", err)
	}
	log.Printf("Deleted Objects: %v\n", delRes.DeletedObjects)

	// Delete multiple objects and the result is not returned.
	objectsToDeleteQuiet := []string{"my-object-3", "my-object-4"}
	_, err = bucket.DeleteObjects(objectsToDeleteQuiet, oss.DeleteObjectsQuiet(true))
	if err != nil {
		log.Fatalf("Failed to delete objects (quiet): %v", err)
	}
	log.Println("Objects deleted quietly")
}

Supprimer des objets par préfixe ou répertoire

Exemple de code pour supprimer des objets par préfixe de nom ou pour supprimer un répertoire entier et son contenu.

Avertissement

Si le préfixe n'est pas spécifié ou est défini sur NULL, tous les objets du bucket sont supprimés. Soyez prudent lorsque vous spécifiez un préfixe lors d'une opération de suppression.

package main

import (
	"log"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance. 
	// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
	// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify the actual region.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Specify the version of the signature algorithm.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the name of the bucket. Example: examplebucket. 
	bucket, err := client.Bucket("examplebucket")
	if err != nil {
		log.Fatalf("Failed to get bucket: %v", err)
	}

	// List all objects whose names contain the specified prefix and delete the objects. 
	marker := oss.Marker("")
	// Specify the prefix of the names of the objects that you want to delete. If you want to delete all objects whose names contain the src prefix, set the prefix to src. After you set the prefix to src, all non-directory objects whose names contain the src prefix, the src directory, and all objects in the src directory are deleted.
	prefix := oss.Prefix("src")
	// If you want to delete only the src directory and all objects in the directory, set the prefix to src/. 
	// prefix := oss.Prefix("src/")
	var totalDeleted int

	for {
		lor, err := bucket.ListObjects(marker, prefix)
		if err != nil {
			log.Fatalf("Failed to list objects: %v", err)
		}

		objects := make([]string, len(lor.Objects))
		for i, object := range lor.Objects {
			objects[i] = object.Key
		}

		// Delete the objects.
		delRes, err := bucket.DeleteObjects(objects, oss.DeleteObjectsQuiet(true))
		if err != nil {
			log.Fatalf("Failed to delete objects: %v", err)
		}

		if len(delRes.DeletedObjects) > 0 {
			log.Fatalf("Some objects failed to delete: %v", delRes.DeletedObjects)
		}

		totalDeleted += len(objects)

		// Update the marker.
		marker = oss.Marker(lor.NextMarker)
		if !lor.IsTruncated {
			break
		}
	}

	log.Printf("Success, total deleted object count: %d\n", totalDeleted)
}

Références

  • Exemple de code complet pour la suppression d'objets : GitHub.

  • Pour plus d'informations sur l'opération API permettant de supprimer un objet, consultez DeleteObject.

  • Référence API pour la suppression de plusieurs objets : DeleteObjects.