Amazon Simple Storage Service
Developer Guide (API Version 2006-03-01)

The AWS Documentation website is getting a new look!
Try it now and let us know what you think. Switch to the new look >>

You can return to the original look by selecting English in the language selector above.

Upload an Object Using the AWS SDK for Java

The following example creates two objects. The first object has a text string as data, and the second object is a file. The example creates the first object by specifying the bucket name, object key, and text data directly in a call to AmazonS3Client.putObject(). The example creates the second object by using a PutObjectRequest that specifies the bucket name, object key, and file path. The PutObjectRequest also specifies the ContentType header and title metadata.

For instructions on creating and testing a working sample, see Testing the Amazon S3 Java Code Examples.

import com.amazonaws.AmazonServiceException; import com.amazonaws.SdkClientException; import com.amazonaws.regions.Regions; import; import; import; import; import; import; public class UploadObject { public static void main(String[] args) throws IOException { Regions clientRegion = Regions.DEFAULT_REGION; String bucketName = "*** Bucket name ***"; String stringObjKeyName = "*** String object key name ***"; String fileObjKeyName = "*** File object key name ***"; String fileName = "*** Path to file to upload ***"; try { //This code expects that you have AWS credentials set up per: // AmazonS3 s3Client = AmazonS3ClientBuilder.standard() .withRegion(clientRegion) .build(); // Upload a text string as a new object. s3Client.putObject(bucketName, stringObjKeyName, "Uploaded String Object"); // Upload a file as a new object with ContentType and title specified. PutObjectRequest request = new PutObjectRequest(bucketName, fileObjKeyName, new File(fileName)); ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentType("plain/text"); metadata.addUserMetadata("x-amz-meta-title", "someTitle"); request.setMetadata(metadata); s3Client.putObject(request); } catch (AmazonServiceException e) { // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); } catch (SdkClientException e) { // Amazon S3 couldn't be contacted for a response, or the client // couldn't parse the response from Amazon S3. e.printStackTrace(); } } }