Path: blob/master/code_examples/java_examples/S3Examples/UploadObject.java
4084 views
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.1// SPDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-s3-developer-guide/blob/master/LICENSE-SAMPLECODE.)23import java.io.File;4import java.io.IOException;56import com.amazonaws.AmazonServiceException;7import com.amazonaws.SdkClientException;8import com.amazonaws.auth.profile.ProfileCredentialsProvider;9import com.amazonaws.services.s3.AmazonS3;10import com.amazonaws.services.s3.AmazonS3ClientBuilder;11import com.amazonaws.services.s3.model.ObjectMetadata;12import com.amazonaws.services.s3.model.PutObjectRequest;1314public class UploadObject {1516public static void main(String[] args) throws IOException {17String clientRegion = "*** Client region ***";18String bucketName = "*** Bucket name ***";19String stringObjKeyName = "*** String object key name ***";20String fileObjKeyName = "*** File object key name ***";21String fileName = "*** Path to file to upload ***";2223try {24AmazonS3 s3Client = AmazonS3ClientBuilder.standard()25.withRegion(clientRegion)26.withCredentials(new ProfileCredentialsProvider())27.build();2829// Upload a text string as a new object.30s3Client.putObject(bucketName, stringObjKeyName, "Uploaded String Object");3132// Upload a file as a new object with ContentType and title specified.33PutObjectRequest request = new PutObjectRequest(bucketName, fileObjKeyName, new File(fileName));34ObjectMetadata metadata = new ObjectMetadata();35metadata.setContentType("text/plain");36metadata.addUserMetadata("x-amz-meta-title", "someTitle");37request.setMetadata(metadata);38s3Client.putObject(request);39}40catch(AmazonServiceException e) {41// The call was transmitted successfully, but Amazon S3 couldn't process42// it, so it returned an error response.43e.printStackTrace();44}45catch(SdkClientException e) {46// Amazon S3 couldn't be contacted for a response, or the client47// couldn't parse the response from Amazon S3.48e.printStackTrace();49}50}51}5253