Topics
This section is a tutorial that walks you step-by-step through many of the major tasks you perform using Amazon S3, including uploading, downloading, and deleting data. To get the most out of this guide, we recommend that you read the following sections in the sequence they're presented.
The HTML version of this guide enables you to hide the text in this section that doesn't pertain to the programming language you are using. There is a language selection menu in the upper-right corner of pages with language-specific text. Select your computer language to show the examples in only that computer language, or select All to show the examples in all available computer languages.

Amazon S3 authentication validates the identity of the party making a request. Authentication ensures that you don't get charged for operations you did not authorize.
Security always relies on a secret. For Amazon S3 (and other AWS services), your secret is
your AWS Secret Access Key. Do not reveal it to anyone even if a request appears to come
from Amazon.com. AWS pairs your AWS Secret Access Key with your AWS Access Key ID. You
include inAmazon S3 requests your AWS Access Key ID and an HMAC SHA-1 value, called the
signature value, calculated using your AWS Secret Access Key.
Amazon S3 verifies that the sender of the request knows the both the AWS Access Key ID and
the corresponding AWS Secret Access Key. Amazon S3 does not process requests where the AWS
Access Key ID and AWS Secret Key do not match.
In the following samples, you simply add your AWS Access Key ID and AWS Secret Key to the sample files. For more information about authentication, go to the Amazon Simple Storage Service Developer Guide.
![]() | Note |
|---|---|
Depending on how you set the access control list (ACL), Amazon S3 can accept anonymous requests. |
To complete the following sections, download the sample files in one of the following computer languages:
For information about the sample, including how to run it, refer to the README file in each sample.
Be sure to also check out the AWS Developer Resource Center, which has a complete collection of code samples, articles, and documentation for building applications using Amazon S3.
Before you can store data in Amazon S3 you need to create a bucket to hold your objects.
You must specify a name for the bucket when you create it. The name can be any string you choose (up to 255 bytes in length) but cannot be the same as any other bucket name already owned by an Amazon S3 user. Keep in mind that the bucket name is visible in any URLs that address your objects. So, you should choose a name that is appropriate in that context.
The following sample code snippets demonstrate how to create an Amazon S3 bucket.
![]() | Note |
|---|---|
For information on other bucket creation options, including how to store data in EU (Ireland) and US-West (Northern California), go to the section, Buckets and Regions, in the Amazon Simple Storage Service Developer Guide. |
To run the sample
Open the AwsCredentials.properties file, which is
in the same directory as the sample file.
For example, the Console sample file is located at aws-java-sdk/samples/AwsConsoleApp/AwsCredentials.properties.
Locate the following section and fill in your Access Key ID and Secret Access Key:
# Fill in your AWS Access Key ID and Secret Access Key # http://aws.amazon.com/security-credentials accessKey =AccessKeyidsecretKey =SecretKey
Save the file.
Open the sample file and replace my-first-s3-bucket with
the bucket name to create.
String bucketName = "my-first-s3-bucket-" + UUID.randomUUID();
Run the sample.
System.out.println("Creating bucket " + bucketName + "\n");
s3.createBucket(bucketName);This example uses AWS libraries for .NET. For more information, see AWS SDK for .NET.
To run the sample
Open the sample file.
Replace bucket-name with the bucket name to create. Also,
replace secretKeyID and secretAccessKeyID with your personal values.
static void CreateABucket()
{
// all future examples assume this:
AmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client(secretKeyID, secretAccessKeyID);
try
{
PutBucketRequest request = new PutBucketRequest();
request.BucketName = "[bucket-name]";
S3Response response = client.PutBucket(request);
// Do something with the response
response.Dispose();
}
catch (AmazonS3Exception ex)
{
// something bad happened
}
}To run the sample
Open the sample file.
Replace bucket-name with the bucket name to
create.
# all future examples assume this:
my $conn =
S3::AWSAuthConnection->new("[aws-access-key-id]", "[aws-secret-access-key]");
my $response = $conn->create_bucket("[bucket-name]");
if ($response->http_response->code == 200) {
# bucket was created
} else {
# something bad happened
}To run the sample
Open the sample file.
Replace bucket-name with the bucket name to
create.
$req =& new HTTP_Request("http://s3.amazonaws.com/[bucket-name]");
$req->setMethod("PUT");
setAuthorizationHeader($req);
$req->sendRequest();
if ($req->getResponseCode() == 200) {
// bucket was created
} else {
// something bad happened
}To run the sample
Open the sample file.
Replace bucket-name with the bucket name to
create.
# all future examples assume this:
conn =
S3::AWSAuthConnection.new("[aws-access-key-id]", "[aws-secret-access-key]")
response = conn.create_bucket("[bucket-name]")
if response.http_response.code == 200
# bucket was created
else
# something bad happened
endTo run the sample
Open the sample file.
Replace bucket-name with the bucket name to
create.
# all future examples assume this:
conn = S3.AWSAuthConnection("[aws-access-key-id]", "[aws-secret-access-key]")
response = conn.create_bucket("[bucket-name]")
if response.http_response.status == 200:
# bucket was created
else:
# something bad happenedThe following is an example of an HTTP request.
# create bucket request PUT /[bucket-name] HTTP/1.0 Date: Wed, 08 Mar 2006 04:06:15 GMT Authorization: AWS [aws-access-key-id]:[header-signature] Host: s3.amazonaws.com # create bucket response HTTP/1.1 200 OK x-amz-id-2: VjzdTviQorQtSjcgLshzCZSzN+7CnewvHA+6sNxR3VRcUPyO5fmSmo8bWnIS52qa x-amz-request-id: 91A8CC60F9FC49E7 Date: Wed, 08 Mar 2006 04:06:15 GMT Location: /[bucket-name] Content-Length: 0 Connection: keep-alive Server: AmazonS3
The following example shows how to list the buckets you own.
To run the sample
Open the AwsCredentials.properties file, which is
in the same directory as the sample file.
For example, the Console sample file is located at aws-java-sdk/samples/AwsConsoleApp/AwsCredentials.properties.
Locate the following section and fill in your Access Key ID and Secret Access Key:
# Fill in your AWS Access Key ID and Secret Access Key # http://aws.amazon.com/security-credentials accessKey =AccessKeyidsecretKey =SecretKey
Save the file.
Run the sample.
System.out.println("Listing buckets");
for (S3Bucket bucket : s3.listBuckets()) {
System.out.println(" - " + bucket.getName());
}
System.out.println();
The following example shows how to delete buckets you own.
To run the sample
Open the AwsCredentials.properties file, which is
in the same directory as the sample file.
For example, the Console sample file is located at aws-java-sdk/samples/AwsConsoleApp/AwsCredentials.properties.
Locate the following section and fill in your Access Key ID and Secret Access Key:
# Fill in your AWS Access Key ID and Secret Access Key # http://aws.amazon.com/security-credentials accessKey =AccessKeyidsecretKey =SecretKey
Save the file.
Open the sample and replace my-first-s3-bucket with the
name of the bucket you own.
String bucketName = "my-first-s3-bucket-" + UUID.randomUUID();
Use the following sample to delete the bucket specified by bucketName.
System.out.println("Deleting bucket " + bucketName + "\n");
s3.deleteBucket(bucketName);
} catch (AmazonServiceException ase) {
System.out.println("Caught an AmazonServiceException, which means your request made it "
+ "to Amazon S3, but was rejected with an error response for some reason.");
System.out.println("Error Message: " + ase.getMessage());
System.out.println("HTTP Status Code: " + ase.getStatusCode());
System.out.println("AWS Error Code: " + ase.getErrorCode());
System.out.println("Error Type: " + ase.getErrorType());
System.out.println("Request ID: " + ase.getRequestId());
} catch (AmazonClientException ace) {
System.out.println("Caught an AmazonClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with S3, "
+ "such as not being able to access the network.");
System.out.println("Error Message: " + ace.getMessage());
}
}Once you create a bucket you can store objects in it. To store objects, you use the
HTTP PUT method. When you store an object, Amazon S3 streams the data to
multiple storage servers in multiple data centers to ensure that the data remains
available in the event of internal network or hardware failure. Each object can hold up
to 5 GB of data.
To write data to Amazon S3, you specify a bucket and a key. The key may be any UTF-8
string. Many developers use a prefix-based, key-naming scheme that lends itself to the
List operation. For example, you can store all of your beach
pictures with keys that begin with the prefix "Pictures/Beach," for example, Pictures/Beach/BigWave.jpg and Pictures/Beach/Dune.png.
There is no distinction between overwriting an existing object and creating a new object. When you send data to a bucket and key, Amazon S3 updates the object. If a write operation gets cut off during upload, Amazon S3 maintains the old data (if any) in the object. If two write requests for the same bucket arrive simultaneously, Amazon S3 orders the requests and stores the data from the most recent request.
You cannot modify or append data to an existing object. Amazon S3 either replaces an existing object or does nothing to it at all.
By default, Amazon S3 stores objects with "private" access control grants that allow only
the bucket owner to read the object later. You can specify other access control
instructions using the flexible access grants detailed in the Amazon Simple Storage Service Developer Guide. One of the
most straightforward and common alternatives to the default access control is to set an
object to be publicly readable. This means that any Internet user can download the
object via a simple standard HTTP URL. For publicly readable objects, Amazon S3 bills
the bucket owner for all data downloads. To make an object publicly readable, include
"x-amz-acl: public-read" in the HTTP header of your PUT
request.
The following sample code snippets demonstrate how to store an Amazon S3 object. To write an object, you must have write access to the bucket.
To run the sample
Open the AwsCredentials.properties file, which is
in the same directory as the sample file.
For example, the Console sample file is located at aws-java-sdk/samples/AwsConsoleApp/AwsCredentials.properties.
Locate the following section and fill in your Access Key ID and Secret Access Key:
# Fill in your AWS Access Key ID and Secret Access Key # http://aws.amazon.com/security-credentials accessKey =AccessKeyidsecretKey =SecretKey
Save the file.
Open the sample file and replace my-first-s3-bucket with
the bucket name to create.
String bucketName = "my-first-s3-bucket-" + UUID.randomUUID();
Replace MyObjectKey with the name of an object you want to
upload into Amazon S3.
Run the sample.
System.out.println("Uploading a new object to S3 from a file\n");
s3.putObject(new PutObjectRequest(bucketName, key, createSampleFile()));
This example uses AWS libraries for .NET. For more information, see AWS SDK for .NET.
To run the sample
Open the sample file.
Replace [bucket-name] with the name of your bucket and
[key-name] with the name of the object. Also, replace
secretKeyID and secretAccessKeyID with your personal values.
Make any changes and run the sample.
static void WritingAnObject()
{
// all future examples assume this:
AmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client(secretKeyID, secretAccessKeyID);
// simple object put
PutObjectRequest request = new PutObjectRequest();
request.WithContentBody("this is a test")
.WithBucketName("[bucket-name]")
.WithKey("[key-name]");
S3Response response = client.PutObject(request);
// put a more complex object with some metadata and http headers.
PutObjectRequest titledRequest = new PutObjectRequest();
titledRequest.WithMetaData("title", "my title")
.WithContentBody("this object has a title")
.WithBucketName("[bucket-name]")
.WithKey("[key-name]");
response = client.PutObject(titledRequest);
//Read response
response.Dispose();
}To run the sample
Open the sample file.
Replace [bucket-name] with the name of your bucket and
[key-name] with the name of the object.
Make any changes and run the sample.
# simple object put
my $response =
$conn->put("[bucket-name]", "[key-name]", S3Object->new("this is a test"));
# put a more complex object with some metadata and http headers.
$response =
$conn->put(
"[bucket-name]",
"[key-name]",
S3Object->new("this is a test", { title => "my title" }),
{ "Content-Type" => "text/plain" });To run the sample
Open the sample file.
Replace [bucket-name] with the name of your bucket and
[key-name] with the name of the object.
Make any changes and run the sample.
$req =& new HTTP_Request("http://s3.amazonaws.com/[bucket-name]/[object-name]");
$req->setMethod("PUT");
$req->setBody("this is a test");
$req->setHeader("Content-Type", "text/plain");
$req->setHeader("x-amz-meta-title", "my title");
setAuthorizationHeader($req);
$req->sendRequest();To run the sample
Open the sample file.
Replace [bucket-name] with the name of your bucket and
[key-name] with the name of the object.
Make any changes and run the sample.
# simple object put
conn.put("[bucket-name]", "[key-name]", S3::S3Object.new("this is a test"));
# put a more complex object with some metadata and http headers.
$conn->put(
"[bucket-name]",
"[key-name]",
S3::S3Object.new("this is a test", { "title" => "my title" }),
{ "Content-Type" => "text/plain" })To run the sample
Open the sample file.
Replace [bucket-name] with the name of your bucket and
[key-name] with the name of the object.
Make any changes and run the sample.
# simple object put
conn.put("[bucket-name]", "[key-name]", S3.S3Object("this is a test"));
# put a more complex object with some metadata and http headers.
$conn->put(
"[bucket-name]",
"[key-name]",
S3.S3Object("this is a test", { "title": "my title" })
{ "Content-Type": "text/plain" })The following is an example of an HTTP request.
# put object request PUT /[bucket-name]/[key-name] HTTP/1.0 Date: Wed, 08 Mar 2006 04:06:16 GMT Authorization: AWS [aws-access-key-id]:[header-signature] Host: s3.amazonaws.com Content-Length: 14 x-amz-meta-title: my title Content-Type: text/plain this is a test # put object response HTTP/1.1 200 OK x-amz-id-2: wc15E1LUrjDZhNtT4QZtsbtadnOMKGjw5QTxkRDVO1owwbA6YoiqJJEuKShopufw x-amz-request-id: 7487CD42C5CA7524 Date: Wed, 08 Mar 2006 04:06:16 GMT ETag: "54b0c58c7ce9f2a8b551351102ee0938" Content-Length: 0 Connection: keep-alive Server: AmazonS3
You can retrieve an ordered list of keys for objects in your bucket using an HTTP
GET request. To help narrow the list, you can specify a key
prefix tol ensure that Amazon S3 returns only keys matching the prefix. For each key
returned, the List operation returns some basic information about
the object represented by the key, including:
The size of the object
A timestamp that specifies when the object was last modified
An identifier for the user that last modified the object
Amazon S3 returns the identifier only if you are the bucket owner
The following sample code snippets demonstrate how to list objects.
To run the sample
Open the AwsCredentials.properties file, which is
in the same directory as the sample file.
For example, the Console sample file is located at aws-java-sdk/samples/AwsConsoleApp/AwsCredentials.properties.
Locate the following section and fill in your Access Key ID and Secret Access Key:
# Fill in your AWS Access Key ID and Secret Access Key # http://aws.amazon.com/security-credentials accessKey =AccessKeyidsecretKey =SecretKey
Save the file.
Open the sample file and replace my-first-s3-bucket with
the bucket name to create.
String bucketName = "my-first-s3-bucket-" + UUID.randomUUID();
Run the sample.
System.out.println("Listing objects");
S3ObjectListing objectListing = s3.listObjects(new ListObjectsRequest()
.withBucketName(bucketName)
.withPrefix("My"));
for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) {
System.out.println(" - " + objectSummary.getKey() + " " +
"(size = " + objectSummary.getSize() + ")");
}
System.out.println(); This example uses AWS libraries for .NET. For more information, see AWS SDK for .NET.
To run the sample
Open the sample file.
Replace [bucket-name] with the name of your bucket. Also,
replace secretKeyID and secretAccessKeyID with your personal values.
Use the following sample to test different list operations.
static void ListingObjects()
{
// all future examples assume this:
AmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client(secretKeyID, secretAccessKeyID);
// simple list
ListObjectsRequest request = new ListObjectsRequest();
request.BucketName = "[bucket-name]";
ListObjectsResponse response = client.ListObjects(request);
foreach (S3Object entry in response.S3Objects)
{
Console.WriteLine("key = {0} size = {1}", entry.Key, entry.Size);
}
// list only things starting with "foo"
request.WithPrefix("foo");
response = client.ListObjects(request);
// list only things that come after "bar" alphabetically
request.WithPrefix("")
.WithMarker("bar");
response = client.ListObjects(request);
// only list 3 things
request.WithPrefix("")
.WithMarker("")
.WithMaxKeys("3");
response = client.ListObjects(request);
response.Dispose();
}
To run the sample
Open the sample file.
Replace bucket-name with the name of your
bucket.
Use the following sample to test different list operations.
# simple list
my $response = $conn->list_bucket("[bucket-name]");
foreach my $entry (@{$response->entries}) {
print "key = $entry->{Key} size = $entry->{Size}\n";
}
# list only things starting with "foo"
$response = $conn->list_bucket("[bucket-name]", {prefix => "foo"});
# list only things that come after "bar" alphabetically
$response = $conn->list_bucket("[bucket-name]", {marker => "bar"});
# only list 3 things
$response = $conn->list_bucket("[bucket-name]", {"max-keys" => 3});To run the sample
Open the sample file.
Replace bucket-name with the name of your
bucket.
Use the following sample to test different list operations.
$req =& new HTTP_Request("http://s3.amazonaws.com/[bucket-name]");
$req->setMethod("GET");
setAuthorizationHeader($req);
$req->sendRequest();
if ($req->getResponseCode() == 200) {
$listXml = $req->getResponseBody();
} else {
// something bad happened
}
// list only things starting with "foo"
$req =& new HTTP_Request("http://s3.amazonaws.com/[bucket-name]/?prefix=foo");
...
// list only things that come after "bar" alphabetically
$req =& new HTTP_Request("http://s3.amazonaws.com/[bucket-name]/?marker=bar");
...
# only list 3 things
$req =& new HTTP_Request("http://s3.amazonaws.com/[bucket-name]/?max-keys=3");To run the sample
Open the sample file.
Replace bucket-name with the name of your
bucket.
Use the following sample to test different list operations.
response = conn.list_bucket("[bucket-name]");
response.entries.each do |entry|
print "key = #{entry.key} size = #{entry.size}\n"
end
# list only things starting with "foo"
response = conn.list_bucket("[bucket-name]", {"prefix" => "foo"});
# list only things that come after "bar" alphabetically
response = conn.list_bucket("[bucket-name]", {"marker" => "bar"});
# only list 3 things
response = conn.list_bucket("[bucket-name]", {"max-keys" => "3"});To run the sample
Open the sample file.
Replace bucket-name with the name of your
bucket.
Use the following sample to test different list operations.
# simple list
response = conn.list_bucket("[bucket-name]");
for entry in response.entries:
print "key = %s size = %d" % (entry.key, entry.size)
# list only things starting with "foo"
response = conn.list_bucket("[bucket-name]", {"prefix": "foo"});
# list only things that come after "bar" alphabetically
response = conn.list_bucket("[bucket-name]", {"marker": "bar"});
# only list 3 things
response = conn.list_bucket("[bucket-name]", {"max-keys" => "3"});The following is an example of an HTTP request.
# list bucket request
GET /[test-bucket] HTTP/1.0
Date: Wed, 08 Mar 2006 04:06:17 GMT
Authorization: AWS [aws-access-key-id]:[header-signature]
Host: s3.amazonaws.com
# list bucket response (xml pretty formatted)
HTTP/1.1 200 OK
x-amz-id-2: 0rSP+1mPucqZ95lYmd53HsgDr6fi2KK8j1uNHz81AngfeOAIaVpNnOBLQ/B9pXJ/
x-amz-request-id: 317FD4EE0A1984DD
Date: Wed, 08 Mar 2006 04:06:17 GMT
Content-Type: application/xml
Connection: close
Server: AmazonS3
<?xml version="1.0" encoding="UTF-8"?>
<ListBucketResult xmlns="http://webservices.amazon.com/schema/request">
<Name>[bucket-name]</Name>
<Prefix/>
<Marker/>
<MaxKeys>1000</MaxKeys>
<IsTruncated>false</IsTruncated>
<Contents>
<Key>>[key-name]</Key>
<LastModified>2006-03-07T20:06:18.000-08:00</LastModified>
<ETag>"54b0c58c7ce9f2a8b551351102ee0938"</ETag>
<Size>14</Size>
<Owner>
<ID>AmazonCustomer|[amazon-id]</ID>
<DisplayName>[display-name]</DisplayName>
</Owner>
<StorageClass>STANDARD<StorageClass>
</Contents>
</ListBucketResult>To read an object, you send an HTTP GET request to the URL (end
point, bucket name, and key) that identifies the object you want to read.
If the object you're fetching is publicly readable, you can read it by pasting its
URL into a browser. You can also place a link to the object on a web page for others to
click. For developers that want to serve URLs to users without having to make their
objects publicly readable, Amazon S3 offers a query-string authentication mechanism for
GET operations that enables you to include the request
signature in the URL rather than in the request header. This
enables you to pre-sign a request and then hand it out to your customers. For more
information about query-string authentication, go to the Amazon Simple Storage Service Developer Guide.
The following sample code snippets demonstrate retrieving an Amazon S3 object.
To run the sample
Open the AwsCredentials.properties file, which is
in the same directory as the sample file.
For example, the Console sample file is located at aws-java-sdk/samples/AwsConsoleApp/AwsCredentials.properties.
Locate the following section and fill in your Access Key ID and Secret Access Key:
# Fill in your AWS Access Key ID and Secret Access Key # http://aws.amazon.com/security-credentials accessKey =AccessKeyidsecretKey =SecretKey
Save the file.
Open the sample file and replace my-first-s3-bucket with
the bucket name to create.
String bucketName = "my-first-s3-bucket-" + UUID.randomUUID();
Replace MyObjectKey with the name of an object you want to
read from Amazon S3.
Run the sample.
GetResponse response = conn.get("[bucket-name]", "[key-name]", null);
String value = response.object.data;
Map metadata = response.object.metadata;
List values = (List)metadata.get("title");
String title = (String)values.get(0);This example uses AWS libraries for .NET. For more information, see AWS SDK for .NET.
To run the sample
Open the sample file.
Replace [bucket-name] with the name of your bucket and
[key-name] with the name of the EC2 key pair name. Also,
replace secretKeyID and secretAccessKeyID with your personal values.
static void ReadingAnObject()
{
// all future examples assume this:
AmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client(secretKeyID, secretAccessKeyID);
GetObjectRequest request = new GetObjectRequest().WithBucketName("[bucket-name").WithKey("[key-name]");
//Consider calling client.GetObjectMetadata so only metadata is brought back
S3Response response = client.GetObject(request);
string title = response.Metadata["title"];
response.Dispose();
}
To run the sample
Open the sample file.
Replace bucket-name with the name of your bucket and
key-name with the name of the object to read.
my $response = $conn->get("[bucket-name]", "[key-name]");
my $data = $response->object->data;
my $metadata = $response->object->metadata;
my $title = $metadata->{title};To run the sample
Open the sample file.
Replace bucket-name with the name of your bucket and
key-name with the name of the object to read.
$req =& new HTTP_Request("http://s3.amazonaws.com/[bucket-name]/[key-name]");
$req->setMethod("GET");
setAuthorizationHeader($req);
$req->sendRequest();
if ($req->getResponseCode() == 200) {
$data = $req->getResponseBody();
} else {
// something bad happened
}To run the sample
Open the sample file.
Replace bucket-name with the name of your bucket and
key-name with the name of the object to read.
response = conn.get("[bucket-name]", "[key-name]");
data = response.object.data
metadata = response.object.metadata
title = metadata["title"]To run the sample
Open the sample file.
Replace bucket-name with the name of your bucket and
key-name with the name of the object to read.
response = conn.get("[bucket-name]", "[key-name]");
data = response.object.data
metadata = response.object.metadata
title = metadata["title"]The following is an example of an HTTP request.
# get object request GET /[bucket-name]/[key-name] HTTP/1.0 Date: Wed, 08 Mar 2006 04:06:18 GMT Authorization: AWS [aws-access-key-id]:[header-signature] Host: s3.amazonaws.com # get object response HTTP/1.1 200 OK x-amz-id-2: FbGpiykb9oJEdJd0bcfwkL6S3lc06X0y7XSeA/GWyRdvlNEZ0irthljxKoeGFfB6 x-amz-request-id: 9298531013923634 Date: Wed, 08 Mar 2006 04:06:18 GMT Last-Modified: Wed, 08 Mar 2006 04:06:16 GMT ETag: "54b0c58c7ce9f2a8b551351102ee0938" x-amz-meta-title: my title Content-Type: text/plain Content-Length: 14 Connection: keep-alive Server: AmazonS3 this is a test
Deleting an object removes the object key from your bucket and makes the object
permanently irretrievable.. To delete an object, send an HTTP DELETE request to the URL that identifies the object you want to delete.
Be sure to include the required, authentication information.
The following sample code snippets how how to delete an Amazon S3 object.
To run the sample
Open the AwsCredentials.properties file, which is
in the same directory as the sample file.
For example, the Console sample file is located at aws-java-sdk/samples/AwsConsoleApp/AwsCredentials.properties.
Locate the following section and fill in your Access Key ID and Secret Access Key:
# Fill in your AWS Access Key ID and Secret Access Key # http://aws.amazon.com/security-credentials accessKey =AccessKeyidsecretKey =SecretKey
Save the file.
Open the sample file and replace my-first-s3-bucket with
the bucket name to create.
String bucketName = "my-first-s3-bucket-" + UUID.randomUUID();
Replace MyObjectKey with the name of an object you want to
delete from Amazon S3.
Run the sample.
System.out.println("Deleting bucket " + bucketName + "\n");
s3.deleteBucket(bucketName);
} catch (AmazonServiceException ase) {
System.out.println("Caught an AmazonServiceException, which means your request made it "
+ "to Amazon S3, but was rejected with an error response for some reason.");
System.out.println("Error Message: " + ase.getMessage());
System.out.println("HTTP Status Code: " + ase.getStatusCode());
System.out.println("AWS Error Code: " + ase.getErrorCode());
System.out.println("Error Type: " + ase.getErrorType());
System.out.println("Request ID: " + ase.getRequestId());
} catch (AmazonClientException ace) {
System.out.println("Caught an AmazonClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with S3, "
+ "such as not being able to access the network.");
System.out.println("Error Message: " + ace.getMessage());
}
}This example uses AWS libraries for .NET. For more information, see AWS SDK for .NET.
To run the sample
Open the sample file.
Replace bucket-name with the name of your bucket and
key-name with the name of the object to delete.
static void DeletingAnObject()
{
// all future examples assume this:
AmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client(secretKeyID, secretAccessKeyID);
try
{
DeleteObjectRequest request = new DeleteObjectRequest();
request.WithBucketName("[bucket-name]")
.WithKey("[key-name]");
DeleteObjectResponse response = client.DeleteObject(request);
response.Dispose();
}
catch (AmazonS3Exception ex)
{
// Something bad happened
}
}
To run the sample
Open the sample file.
Replace bucket-name with the name of your bucket and
key-name with the name of the object to delete.
$conn->delete("[bucket-name]", "[key-name]");
if ($response->http_response->code == 204) {
# object was deleted
} else {
# something bad happened
}To run the sample
Open the sample file.
Replace bucket-name with the name of your bucket and
key-name with the name of the object to delete.
$req =& new HTTP_Request("http://s3.amazonaws.com/[bucket-name]/[key-name]");
$req->setMethod("DELETE");
setAuthorizationHeader($req);
$req->sendRequest();
if ($req->getResponseCode() == 204) {
// bucket was deleted
} else {
// something bad happened
}To run the sample
Open the sample file.
Replace bucket-name with the name of your bucket and
key-name with the name of the object to delete.
conn.delete("[bucket-name]", "[key-name]");
if response.http_response.status == 204
# object was deleted
else
# something bad happened
endTo run the sample
Open the sample file.
Replace bucket-name with the name of your bucket and
key-name with the name of the object to delete.
conn.delete("[bucket-name]", "[key-name]");
if response.http_response.status == 204:
# object was deleted
else:
# something bad happenedThe following is an example of an HTTP request.
# delete object request DELETE /[bucket-name]/[key-name] HTTP/1.0 Date: Wed, 08 Mar 2006 04:06:19 GMT Authorization: AWS [aws-access-key-id]:[header-signature] Host: s3.amazonaws.com # delete object response HTTP/1.1 204 No Content x-amz-id-2: RvtfYQa0bFoavLma0eYJ1tgK17N/N6AWs6VQOUBSdzNTXwTL5W9BGIxt+D6gK+7I x-amz-request-id: 6F7B7DB829785419 Date: Wed, 08 Mar 2006 04:06:19 GMT Connection: keep-alive Server: AmazonS3
The following example creates a temporary file with text data to demonstrate uploading a file
To run the sample
Open the AwsCredentials.properties file, which is
in the same directory as the sample file.
For example, the Console sample file is located at aws-java-sdk/samples/AwsConsoleApp/AwsCredentials.properties.
Locate the following section and fill in your Access Key ID and Secret Access Key:
# Fill in your AWS Access Key ID and Secret Access Key # http://aws.amazon.com/security-credentials accessKey =AccessKeyidsecretKey =SecretKey
Save the file.
Open the sample file and replace my-first-s3-bucket with
the bucket name to create.
String bucketName = "my-first-s3-bucket-" + UUID.randomUUID();
Replace MyObjectKey with the name of an object you want to
upload into Amazon S3.
Use the following sample to test different list operations.
private static File createSampleFile() throws IOException {
File file = File.createTempFile("aws-java-sdk-", ".txt");
file.deleteOnExit();
Writer writer = new OutputStreamWriter(new FileOutputStream(file));
writer.write("abcdefghijklmnopqrstuvwxyz\n");
writer.write("01234567890112345678901234\n");
writer.write("!@#$%^&*()-=[]{};':',.<>/?\n");
writer.write("01234567890112345678901234\n");
writer.write("abcdefghijklmnopqrstuvwxyz\n");
writer.close();
return file;
}
The return is a newly created temporary file that contains text data.
You
The following sample code .
To run the sample
Open the AwsCredentials.properties file, which is
in the same directory as the sample file.
For example, the Console sample file is located at aws-java-sdk/samples/AwsConsoleApp/AwsCredentials.properties.
Locate the following section and fill in your Access Key ID and Secret Access Key:
# Fill in your AWS Access Key ID and Secret Access Key # http://aws.amazon.com/security-credentials accessKey =AccessKeyidsecretKey =SecretKey
Save the file.
Open the sample file and replace my-first-s3-bucket with
the bucket name to create.
String bucketName = "my-first-s3-bucket-" + UUID.randomUUID();
Replace MyObjectKey with the name of an object you want to
upload into Amazon S3.
In the following code sample, set input to the text
you want to display as the input stream.
Use the following sample to test different list operations.
private static void displayTextInputStream(InputStream input) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
while (true) {
String line = reader.readLine();
if (line == null) break;
System.out.println(" " + line);
}
System.out.println();
}
} Your input is important to us to help make our documentation helpful and easy to use. Please take a minute to give us your feedback on how well we were able to help you get started with Amazon S3. Just click this Feedback link. Thank you.
Now that you've used this guide to upload, download, delete, and list data in Amazon S3, you've become familiar with the architecture of the system, some of its basic functionality, and the kind of responses you can expect. The next section explains how to learn more about Amazon S3 and how to implement advanced Amazon S3 functionality in your applications.