Remove Object from Bucket
Using this codes, you can delete the current version of an object.
Components
- Bucket Name
- Object Name
- .NET
- PHP
- Python
- Javascript
- GO
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache - 2.0
using Amazon;
using Amazon.S3;
using Amazon.S3.Model;
using System;
using System.Threading.Tasks;
using System.Reflection;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace DeleteObject
{
class DeleteObject
{
private static IAmazonS3 _s3Client;
private const string BUCKET_NAME = "<BUCKET_NAME>";
private const string OBJECT_NAME = "<OBJECT_NAME>";
static void Main()
{
var awsCredentials = new Amazon.Runtime.BasicAWSCredentials("<ACCESS-KEY>", "<SECRET-KEY>");
var config = new AmazonS3Config { ServiceURL = "<ENDPOINT>" };
_s3Client = new AmazonS3Client(awsCredentials, config);
DeleteObjectHelper().Wait();
}
private static async Task DeleteObjectHelper()
{
try
{
// Create the request
DeleteObjectsRequest request = new ()
{
BucketName = BUCKET_NAME,
Objects = new List<KeyVersion> { new KeyVersion() { Key = OBJECT_NAME, VersionId = null } }
};
// Submit the request
DeleteObjectsResponse response = await _s3Client.DeleteObjectsAsync(request);
Console.WriteLine(JsonConvert.SerializeObject(response, Formatting.Indented));
Console.WriteLine($"Object {OBJECT_NAME} successfully deleted from {BUCKET_NAME} bucket");
}
catch (AmazonS3Exception amazonS3Exception)
{
Console.WriteLine("An AmazonS3Exception was thrown. Exception: " + amazonS3Exception.ToString());
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.ToString());
}
}
}
}
<?php
require('client.php');
$object = $client-> deleteObject ([
'Bucket' => $config['sample_bucket'],
'Key' => 'file-name.png']);
import boto3
import logging
from botocore.exceptions import ClientError
logging.basicConfig(level=logging.INFO)
try:
s3_resource = boto3.resource(
's3',
endpoint_url='endpoint_url',
aws_access_key_id='access_key',
aws_secret_access_key='secret_key'
)
except Exception as exc:
logging.error(exc)
else:
try:
# bucket
bucket_name = 'sample_bucket_name'
object_name = 'object_name.txt'
bucket = s3_resource.Bucket('bucket_name')
object = bucket.Object(object_name)
response = object.delete(
VersionId='string',
)
except ClientError as e:
logging.error(e)
// Import required AWS SDK clients and commands for Node.js
const { S3Client, DeleteObjectCommand } = require('@aws-sdk/client-s3');
// Create an S3 client service object
const s3 = new S3Client({
region: 'default',
endpoint: 'endpoint_url',
credentials: {
accessKeyId: 'access_key',
secretAccessKey: 'secret_key',
},
});
// call S3 to retrieve upload file to specified bucket
const run = async () => {
try {
const data = await s3.send(
new DeleteObjectCommand({
Bucket: 'sample-bucket',
Key: 'file.png',
// VersionId: 'version2.2',
})
);
console.log('Success', data);
} catch (err) {
console.log('Error', err);
}
};
run();
package main
import (
"fmt"
"os"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
)
// Deletes the specified object in the specified S3 Bucket in the region configured in the shared config
// or AWS_REGION environment variable.
//
// Usage:
// go run s3_delete_object BUCKET_NAME OBJECT_NAME
func main() {
if len(os.Args) != 3 {
exitErrorf("Bucket and object name required\nUsage: %s bucket_name object_name",
os.Args[0])
}
bucket := os.Args[1]
obj := os.Args[2]
// Initialize a session in us-west-2 that the SDK will use to load
// credentials from the shared credentials file ~/.aws/credentials.
sess, err := session.NewSession(&aws.Config{
Credentials: credentials.NewStaticCredentials("<ACCESS_KEY>", "<SECRET_KEY>", ""),
})
svc := s3.New(sess, &aws.Config{
Region: aws.String("default"),
Endpoint: aws.String("<ENDPOINT_URL>"),
})
// Delete the item
_, err = svc.DeleteObject(&s3.DeleteObjectInput{Bucket: aws.String(bucket), Key: aws.String(obj)})
if err != nil {
exitErrorf("Unable to delete object %q from bucket %q, %v", obj, bucket, err)
}
err = svc.WaitUntilObjectNotExists(&s3.HeadObjectInput{
Bucket: aws.String(bucket),
Key: aws.String(obj),
})
if err != nil {
exitErrorf("Error occurred while waiting for object %q to be deleted, %v", obj, err)
}
fmt.Printf("Object %q successfully deleted\n", obj)
}
func exitErrorf(msg string, args ...interface{}) {
fmt.Fprintf(os.Stderr, msg+"\n", args...)
os.Exit(1)
}
The following command can be used to execute the aforementioned code, presuming the code file is called s3_delete_object.go:
go run s3_delete_object BUCKET_NAME OBJECT_NAME