Created
February 11, 2017 18:08
-
-
Save larikraun/59212bd10ecf36e2a81356bbde809d58 to your computer and use it in GitHub Desktop.
Snippet to Connect to Amazon S3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
String filePath = "PATH_TO_FILE"; // the path of the image/path you want to upload. | |
File file = new File(filePath); | |
String MY_PICTURE_BUCKET = "BUCKET_NAME"; //the name of the bucket you want to create. This name must be unique | |
String MY_IDENTITY_POOL_ID = "IDENTITY_POOL_ID"; //the id you just got from cognito console. | |
CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider( | |
MainActivity.this, // Application Context | |
MY_IDENTITY_POOL_ID, // Identity Pool ID | |
Regions.US_EAST_1 // Region enum | |
); | |
AmazonS3Client s3Client = new AmazonS3Client(credentialsProvider); | |
if (!s3Client.doesBucketExist(MY_PICTURE_BUCKET)) { //bucket names must be unique. | |
s3Client.createBucket(MY_PICTURE_BUCKET); | |
} | |
String MY_PICTURE_NAME = file.getName(); | |
//This will upload the file with the fileName | |
PutObjectRequest por = new PutObjectRequest(MY_PICTURE_BUCKET, MY_PICTURE_NAME, file); | |
if (!s3Client.doesObjectExist(MY_PICTURE_BUCKET, MY_PICTURE_NAME)) { //object name must be unique. | |
s3Client.putObject(por); | |
} | |
//This will fetch the object with the fileName in the bucketName. This snippet assumes that the file coming is an image. | |
GetObjectRequest gor = new GetObjectRequest(bucketName, fileName); | |
Bitmap bmp = null; | |
if (s3Client.doesObjectExist(bucketName, fileName)) { | |
try { | |
S3Object getResponse = s3Client.getObject(gor); | |
InputStream is = getResponse.getObjectContent(); | |
bmp = BitmapFactory.decodeStream(is); | |
is.close(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment