All Products
Search
Document Center

Object Storage Service:Delete objects

Last Updated:Dec 20, 2023

You can temporarily or permanently delete an object from a versioning-enabled bucket based on whether you specify the version ID of the object in the request. In addition, you can temporarily or permanently delete an object, multiple objects, or objects whose names contain a specific prefix from a versioning-enabled bucket.

Usage notes

  • In this topic, the public endpoint of the China (Hangzhou) region is used. If you want to access OSS by using other Alibaba Cloud services in the same region as OSS, use an internal endpoint. For more information about the regions and endpoints supported by OSS, see Regions and endpoints.

  • In this topic, access credentials are obtained from environment variables. For more information about how to configure access credentials, see Configure access credentials.

  • In this topic, an OSSClient instance is created by using an OSS endpoint. If you want to create an OSSClient instance by using custom domain names or Security Token Service (STS), see Initialization.

  • To delete an object, you must have the oss:DeleteObject permission. For more information, see Attach a custom policy to a RAM user.

Delete operations on a versioning-enabled bucket

When you delete an object from a versioning-enabled bucket, you must determine whether to specify a version ID in the request.

  • Delete an object without specifying a version ID (temporary deletion)

    By default, if you do not specify the version ID of the object that you want to delete in the request, OSS does not delete the current version of the object but adds a delete marker to the object as the new current version. If you perform the GetObject operation on the object, OSS identifies the current version of the object as a delete marker and returns 404 Not Found. In addition, x-oss-delete-marker and x-oss-version-id that indicates the version ID of the delete marker are included in the response.

    If the value of x-oss-delete-marker is true, the value of x-oss-version-id is the version ID of a delete marker.

    For more information about how to restore a deleted object, see Restore objects.

  • Delete an object by specifying a version ID (permanent deletion)

    If you specify the version ID of the object that you want to delete in the request, OSS permanently deletes the specified version of the object based on the versionId parameter specified in params. To delete the version whose ID is null, add params['versionId'] = "null" to params. OSS identifies the string "null" as the ID of the version to permanently delete and deletes the version whose ID is null.

Delete an object

The following examples show how to permanently or temporarily delete an object from a versioning-enabled bucket.

  • Permanently delete an object by specifying its version ID

    The following sample code provides an example on how to permanently delete an object from a versioning-enabled bucket by specifying its version ID:

    package main
    
    import (
      "fmt"
      "os"
    
      "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 {
            fmt.Println("Error:", err)
            os.Exit(-1)
        }
    
        // 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. 
        client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
        if err != nil {
           fmt.Println("Error:", err)
           os.Exit(-1)
      }
    
      // Specify the name of the bucket. 
      bucket, err := client.Bucket("yourBucketName")
      if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
      }
      // Specify the full path of the object. Do not include the bucket name in the full path. 
      // Set yourObjectVersionId to the version ID of the object. If this parameter is specified, the object with the specified version ID is permanently deleted. 
      err = bucket.DeleteObject("youObjectName", oss.VersionId("yourObjectVersionId"))
      if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
      }
    }
  • Temporarily delete an object without specifying its version ID

    The following sample code provides an example on how to temporarily delete an object from a versioning-enabled bucket without specifying its version ID:

    package main
    
    import (
    	"fmt"
    	"net/http"
    	"os"
    
    	"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 {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    
    	// 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. 
    	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    
    	// Specify the name of the bucket. 
    	bucket, err := client.Bucket("yourBucketName")
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    
    	var retHeader http.Header
    	// Temporarily delete an object without specifying its version ID. A delete marker is added to the object. 
    	// Specify the full path of the object. Do not include the bucket name in the full path. 
    	err = bucket.DeleteObject("youObjectName", oss.GetResponseHeader(&retHeader))
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    
    	// Display the information about the delete marker. 
    	fmt.Println("x-oss-version-id:", oss.GetVersionId(retHeader))
    	fmt.Println("x-oss-delete-marker:", oss.GetDeleteMark(retHeader))
    }
    

Delete multiple objects

The following examples show how to permanently or temporarily delete multiple objects or delete markers from a versioning-enabled bucket.

  • Permanently delete multiple objects by specifying their version IDs

    The following sample code provides an example on how to permanently delete multiple objects from a versioning-enabled bucket by specifying their version IDs:

    package main
    
    import (
      "fmt"
      "os"
    
      "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 {
            fmt.Println("Error:", err)
            os.Exit(-1)
        }
    
        // 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. 
        client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
        if err != nil {
           fmt.Println("Error:", err)
           os.Exit(-1)
      }
    
      // Specify the name of the bucket. 
      bucket, err := client.Bucket("yourBucketName")
      if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
      }
    
      // Specify the version IDs of the objects that you want to delete. 
      keyArray := []oss.DeleteObject{
        oss.DeleteObject{Key: "objectName1", VersionId:"objectVersionId1"},
        oss.DeleteObject{Key: "objectName2", VersionId:"objectVersionId2"},
      }
    
      // Delete the objects with the specified version IDs. 
      ret, err := bucket.DeleteObjectVersions(keyArray)
      if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
      }
      // Display the information about the deleted objects. 
      for _, object := range ret.DeletedObjectsDetail {
        fmt.Println("Key:", object.Key, "\n VersionId:", object.VersionId)
      }
    }
  • Permanently delete multiple delete markers by specifying their version IDs

    The following sample code provides an example on how to permanently delete multiple delete markers from a versioning-enabled bucket by specifying their version IDs:

    package main
    
    import (
      "fmt"
      "os"
    
      "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 {
            fmt.Println("Error:", err)
            os.Exit(-1)
        }
    
        // 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. 
        client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
        if err != nil {
           fmt.Println("Error:", err)
           os.Exit(-1)
      }
    
      // Specify the name of the bucket. 
      bucket, err := client.Bucket("yourBucketName")
      if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
      }
    
      // Specify the version IDs of the delete markers that you want to delete. 
      keyArray := []oss.DeleteObject{
        oss.DeleteObject{Key: "objectName1", VersionId:"objectVersionId1"},
        oss.DeleteObject{Key: "objectName2", VersionId:"objectVersionId2"},
      }
    
      // Delete the specified delete markers. 
      ret, err := bucket.DeleteObjectVersions(keyArray)
      if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
      }
      // Display the information about the delete markers. 
      for _, object := range ret.DeletedObjectsDetail {
        fmt.Println("key:", object.Key, "\n versionId:", object.VersionId, "\n DeleteMarker:", object.DeleteMarker, "\nDeleteMarkerVersionId", object.DeleteMarkerVersionId)
      }
    }
  • Temporarily delete multiple objects without specifying their version IDs

    The following sample code provides an example on how to temporarily delete multiple objects from a versioning-enabled bucket without specifying their version IDs:

    package main
    
    import (
      "fmt"
      "os"
    
      "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 {
            fmt.Println("Error:", err)
            os.Exit(-1)
        }
    
        // 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. 
        client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
        if err != nil {
           fmt.Println("Error:", err)
           os.Exit(-1)
      }
    
      // Specify the name of the bucket. 
      bucket, err := client.Bucket("yourBucketName")
      if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
      }
    
      // Temporarily delete multiple objects without specifying their version IDs. Delete markers are added to the objects. 
      keyArray := []oss.DeleteObject{
        oss.DeleteObject{Key: "objectName1"},
        oss.DeleteObject{Key: "objectName2"},
      }
    
      res, err := bucket.DeleteObjectVersions(keyArray)
      if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
      }
      // Display the information about the delete markers that are added to the objects. 
      for _, object := range res.DeletedObjectsDetail {
        fmt.Println("key:", object.Key, "\n DeleteMarker:", object.DeleteMarker, "\nDeleteMarkerVersionId", object.DeleteMarkerVersionId)
      }
    }

Delete objects whose names contain a specific prefix

The following sample code provides an example on how to delete objects whose names contain a specific prefix:

package main

import (
    "fmt"
    "os"

    "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 {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }

    // 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. 
    client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }

    // Specify the name of the bucket. 
    bucket, err := client.Bucket("yourBucketName")
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }

    // List and delete the objects whose names contain the specified prefix. 
    prefix := oss.Prefix("yourObjectPrefix")
    marker := oss.KeyMarker("")
    version := oss.VersionIdMarker("")

    for {
        lor, err := bucket.ListObjectVersions(marker, prefix, version)
        if err != nil {
            fmt.Println("Error:", err)
            os.Exit(-1)
        }

        objects := []oss.DeleteObject{}
        for _, object := range lor.ObjectDeleteMarkers {
            objects = append(objects, oss.DeleteObject{
                Key:       object.Key,
                VersionId: object.VersionId,
            })
        }

        for _, object := range lor.ObjectVersions {
            objects = append(objects, oss.DeleteObject{
                Key:       object.Key,
                VersionId: object.VersionId,
            })
        }

        delRes, err := bucket.DeleteObjectVersions(objects, oss.DeleteObjectsQuiet(true))
        if err != nil {
            fmt.Println("Error:", err)
            os.Exit(-1)
        }

        if len(delRes.DeletedObjectsDetail) > 0 {
            fmt.Println("these objects deleted failure,", delRes.DeletedObjectsDetail)
            os.Exit(-1)
        }

        prefix = oss.Prefix(lor.Prefix)
        marker = oss.KeyMarker(lor.NextKeyMarker)
        version = oss.VersionIdMarker(lor.NextVersionIdMarker)
        if !lor.IsTruncated {
            break
        }
    }
    fmt.Printf("delete success\n")
}

References

  • For more information about the API operation that you can call to delete an object, see DeleteObject.

  • For more information about the API operation that you can call to delete multiple objects, see DeleteMultipleObjects.