Tous les produits
Search
Centre de documentation

Object Storage Service:Supprimer des fichiers (Go SDK V1)

Dernière mise à jour :Aug 18, 2026

Pour les buckets dont le versioning est activé, OSS prend en charge la suppression logique et la suppression définitive des objets. Le type de suppression dépend de la présence ou non d'un versionId. Cette fonctionnalité permet de supprimer un objet unique, plusieurs objets ou des objets partageant un préfixe spécifique.

Notes

  • Cette rubrique utilise l'endpoint 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 endpoint interne. Pour plus d'informations sur les régions et les endpoints OSS, consultez Régions et endpoints.

  • Dans cette rubrique, les identifiants d'accès sont récupérés depuis les 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.

Comportement de suppression avec le versioning

Cette section décrit le comportement de suppression des objets lorsque le versioning est activé.

  • Si vous ne spécifiez pas de versionId (suppression logique) :

    Lorsque vous supprimez un objet sans spécifier de versionId, la version actuelle de l'objet n'est pas supprimée. À la place, OSS insère un marqueur de suppression pour la version actuelle. Lors d'une opération GetObject, OSS détecte que la version actuelle est un marqueur de suppression et renvoie 404 Not Found. La réponse inclut également l'en-tête x-oss-delete-marker = true ainsi que le numéro de version du nouveau marqueur de suppression dans x-oss-version-id.

    Une valeur true pour x-oss-delete-marker indique que la version correspondant au x-oss-version-id renvoyé est un marqueur de suppression.

    Pour savoir comment restaurer un objet supprimé logiquement, consultez Restaurer des fichiers.

  • Si vous spécifiez un versionId (suppression définitive) :

    Lorsque vous spécifiez un versionId lors d'une opération de suppression, OSS supprime définitivement la version correspondant au paramètre versionId dans params. Pour supprimer la version dont l'ID est « null », ajoutez params['versionId'] = "null" au paramètre params.

Exemple de code

Supprimer un seul fichier

Les exemples de code suivants montrent comment supprimer définitivement ou logiquement un seul objet.

Supprimer un objet en spécifiant un versionId

Le code suivant montre comment supprimer définitivement un objet en spécifiant un versionId :

package main

import (
	"log"

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

func main() {
	// Obtain access credentials from environment variables. Before you run this 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.
	// Set yourEndpoint to the Endpoint of the bucket. For example, for a bucket in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the Endpoint as needed.
	// Set yourRegion to the region where the bucket is located. For example, for a bucket in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Set the signature version.
	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)
	}

	// Set yourBucketName to the name of the bucket.
	bucketName := "yourBucketName"
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket '%s': %v", bucketName, err)
	}

	// Set youObjectName to the full path of the object. Do not include the bucket name.
	// Set yourObjectVersionId to the versionId of the object. After you specify the versionId, the object of this version is permanently deleted.
	objectName := "yourObjectName"
	objectVersionId := "yourObjectVersionId"
	err = bucket.DeleteObject(objectName, oss.VersionId(objectVersionId))
	if err != nil {
		log.Fatalf("Failed to delete object '%s' with version ID '%s': %v", objectName, objectVersionId, err)
	}

	log.Println("Object deleted successfully.")
}

Supprimer un objet sans spécifier de versionId

Le code suivant montre comment supprimer logiquement un objet sans spécifier de versionId :

package main

import (
	"log"
	"net/http"

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

func main() {
	// Obtain access credentials from environment variables. Before you run this 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.
	// Set yourEndpoint to the Endpoint of the bucket. For example, for a bucket in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the Endpoint as needed.
	// Set yourRegion to the region where the bucket is located. For example, for a bucket in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Set the signature version.
	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)
	}

	// Set yourBucketName to the name of the bucket.
	bucketName := "yourBucketName"
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket '%s': %v", bucketName, err)
	}

	// Soft delete the object without specifying a versionId. This operation adds a delete marker to the object.
	// Set youObjectName to the full path of the object. Do not include the bucket name.
	objectName := "yourObjectName"
	var retHeader http.Header
	err = bucket.DeleteObject(objectName, oss.GetResponseHeader(&retHeader))
	if err != nil {
		log.Fatalf("Failed to delete object '%s': %v", objectName, err)
	}

	// Print the delete marker information.
	log.Printf("x-oss-version-id: %s", oss.GetVersionId(retHeader))
	log.Printf("x-oss-delete-marker: %t", oss.GetDeleteMark(retHeader))

	log.Println("Object deleted successfully.")
}

Supprimer plusieurs fichiers

Les exemples de code suivants montrent comment supprimer définitivement ou logiquement plusieurs objets ou marqueurs de suppression.

Supprimer définitivement plusieurs objets en spécifiant des versionIds

Le code suivant montre comment supprimer définitivement plusieurs objets en spécifiant leurs versionIds :

package main

import (
	"log"

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

func main() {
	// Obtain access credentials from environment variables. Before you run this 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.
	// Set yourEndpoint to the Endpoint of the bucket. For example, for a bucket in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the Endpoint as needed.
	// Set yourRegion to the region where the bucket is located. For example, for a bucket in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Set the signature version.
	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)
	}

	// Set yourBucketName to the name of the bucket.
	bucketName := "yourBucketName"
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket '%s': %v", bucketName, err)
	}

	// Specify the versionIds of the objects to be permanently deleted.
	keyArray := []oss.DeleteObject{
		{Key: "objectName1", VersionId: "objectVersionId1"},
		{Key: "objectName2", VersionId: "objectVersionId2"},
	}

	// Delete the specified object versions.
	ret, err := bucket.DeleteObjectVersions(keyArray)
	if err != nil {
		log.Fatalf("Failed to delete objects: %v", err)
	}

	// Print the information about the deleted objects.
	for _, object := range ret.DeletedObjectsDetail {
		log.Printf("Key: %s, VersionId: %s", object.Key, object.VersionId)
	}

	log.Println("Objects deleted successfully.")
}

Supprimer définitivement plusieurs marqueurs de suppression en spécifiant des versionIds

Le code suivant montre comment supprimer définitivement plusieurs marqueurs de suppression en spécifiant leurs versionIds :

package main

import (
	"log"

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

func main() {
	// Obtain access credentials from environment variables. Before you run this 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.
	// Set yourEndpoint to the Endpoint of the bucket. For example, for a bucket in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the Endpoint as needed.
	// Set yourRegion to the region where the bucket is located. For example, for a bucket in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Set the signature version.
	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)
	}

	// Set yourBucketName to the name of the bucket.
	bucketName := "yourBucketName"
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket '%s': %v", bucketName, err)
	}

	// Specify the version information of the delete markers.
	keyArray := []oss.DeleteObject{
		{Key: "objectName1", VersionId: "objectVersionId1"},
		{Key: "objectName2", VersionId: "objectVersionId2"},
	}

	// Permanently delete multiple delete markers by specifying their versionIds.
	ret, err := bucket.DeleteObjectVersions(keyArray)
	if err != nil {
		log.Fatalf("Failed to delete objects: %v", err)
	}

	// Print the information about the deleted objects and delete markers.
	for _, object := range ret.DeletedObjectsDetail {
		log.Printf("Key: %s, VersionId: %s, DeleteMarker: %t, DeleteMarkerVersionId: %s",
			object.Key, object.VersionId, object.DeleteMarker, object.DeleteMarkerVersionId)
	}

	log.Println("Objects deleted successfully.")
}

Supprimer logiquement plusieurs objets sans spécifier de versionIds

Le code suivant montre comment supprimer logiquement plusieurs objets sans spécifier leurs versionIds :

package main

import (
	"log"

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

func main() {
	// Obtain access credentials from environment variables. Before you run this 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.
	// Set yourEndpoint to the Endpoint of the bucket. For example, for a bucket in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the Endpoint as needed.
	// Set yourRegion to the region where the bucket is located. For example, for a bucket in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Set the signature version.
	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)
	}

	// Set yourBucketName to the name of the bucket.
	bucketName := "yourBucketName"
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket '%s': %v", bucketName, err)
	}

	// Soft delete multiple objects without specifying their versionIds. This operation adds delete markers to the objects.
	keyArray := []oss.DeleteObject{
		{Key: "objectName1"},
		{Key: "objectName2"},
	}

	// Execute the delete operation.
	res, err := bucket.DeleteObjectVersions(keyArray)
	if err != nil {
		log.Fatalf("Failed to delete objects: %v", err)
	}

	// Print the delete markers of the objects.
	for _, object := range res.DeletedObjectsDetail {
		log.Printf("Key: %s, DeleteMarker: %t, DeleteMarkerVersionId: %s",
			object.Key, object.DeleteMarker, object.DeleteMarkerVersionId)
	}

	log.Println("Objects deleted successfully.")
}

Références

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

  • Pour plus d'informations sur l'opération API permettant de supprimer une version spécifiée d'un objet, consultez DeleteObjectVersions.