All Products
Search
Document Center

Object Storage Service:Delete objects

Last Updated:Sep 11, 2023

You can delete one or more objects at a time, delete objects whose names contain a specified prefix, or delete a specified directory and all objects in the directory.

Warning

Deleted objects cannot be recovered. Exercise caution when you delete objects.

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 Common examples of RAM policies.

Delete a single object

The following sample code provides an example on how to delete the exampleobject.txt object from the examplebucket bucket:

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. 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"

    bucket, err := client.Bucket(bucketName)
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }

    // Delete the object. 
    err = bucket.DeleteObject(objectName)
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }
}

Delete multiple objects

You can delete up to 1,000 objects at a time. You can delete multiple specified objects, objects whose names contain a specified prefix, or a specified directory and all objects in the directory.

You can also configure lifecycle rules to automatically delete objects. For more information, see Lifecycle rules based on the last modification time.

Delete multiple specified objects

The following sample code provides an example on how to delete multiple specified objects:

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. Example: examplebucket. 
    bucketName := "examplebucket"
    
    bucket, err := client.Bucket(bucketName)
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }

    // Specify the full paths of the objects that you want to delete. Do not include the bucket name in the full paths. 
    delRes, err := bucket.DeleteObjects([]string{"my-object-1", "my-object-2"})
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }    
    fmt.Println("Deleted Objects:", delRes.DeletedObjects)

    // Set oss.DeleteObjectsQuiet to true. The value true indicates that the result about the deletion is not returned. 
    _, err = bucket.DeleteObjects([]string{"my-object-3", "my-object-4"},
    oss.DeleteObjectsQuiet(true))
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }
}

Delete multiple objects with a specified object name prefix or in a specified directory

The following sample code provides an example on how to delete multiple objects with a specified name prefix and how to delete a specified directory and all objects in the directory.

Warning

If the prefix is not specified or is set to NULL in the following code, all objects in the bucket are deleted. Exercise caution when you specify a prefix in a delete operation.

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. Example: examplebucket. 
    bucket, err := client.Bucket("examplebucket")
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }

    // 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/")
    count := 0
    for {
        lor, err := bucket.ListObjects(marker, prefix)
        if err != nil {
            fmt.Println("Error:", err)
            os.Exit(-1)
        }

        objects := []string{}
        for _, object := range lor.Objects {
            objects = append(objects, object.Key)
        }
        // Set oss.DeleteObjectsQuiet to true. The value true indicates that the result about the deletion is not returned. 
        delRes, err := bucket.DeleteObjects(objects, oss.DeleteObjectsQuiet(true))
        if err != nil {
            fmt.Println("Error:", err)
            os.Exit(-1)
        }

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

        count += len(objects)

        prefix = oss.Prefix(lor.Prefix)
        marker = oss.Marker(lor.NextMarker)
        if !lor.IsTruncated {
            break
        }
    }
    fmt.Printf("success,total delete object count:%d\n", count)
}

References

  • For more information about the complete sample code that is used to delete objects, visit GitHub.

  • 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.