Upload images to the AWS from android

This  will help you with  how to create an s3 bucket in AWS, how to get  all the credentials to upload images to that bucket from an android device and  to get the image url   for the further use.

 

 

What is this all about?
This is a blog which help you to know how to upload the file to the AWS server from the android mobile.

Prerequisites:

  • AWS bucket
  • AWS access key Id
  • AWS secret access key
  • AWS server region
  • Basic knowledge of the android studio

To get the prerequisites follow the instructions:

AWS bucket:

To get the AWS bucket first you have to log in to the AWS server then you have to create the bucket  just going into s3 then there will be option to create bucket

 

screen-shot-2016-10-20-at-1-13-47-pm

 

Now create you bucket with the name you want.

 

screen-shot-2016-10-20-at-6-18-54-pm

 

After creating the the bucket create the folder inside the bucket if you want to.

 

screen-shot-2016-10-20-at-1-16-30-pm

 

then that will be you path as well as AWS bucket.

AWS access key Id and AWS secret access key:

To get the the server key and secret key  on the top right side of the navigation bar you will find the username with the down arrow mark click on it and select the security credentials.

 

screen-shot-2016-10-20-at-6-26-06-pm

 

after selecting the security credentials select the Access Keys (Access Key ID and Secret Access Key) option

 

screen-shot-2016-10-20-at-6-43-14-pm

 

then  create new access key were you will get the server access key and id  on clicking the show access key and copy that.

 

screen-shot-2016-10-20-at-6-42-01-pm
and thats your secret access key and id.

AWS server region:

This is to know in which region is you server going to locate right now mine is located as singapore.

 

screen-shot-2016-10-20-at-5-25-13-pm
also know as ap-southeast-1(AWS Regions and Endpoints) which is required.

Now at mobile side Implementation:

Step 1:

Your app buid.gradle should have this dependencies.

dependencies {

 ...  

compile 'com.amazonaws:aws-android-sdk-core:2.2.+'

compile 'com.amazonaws:aws-android-sdk-cognito:2.2.+'

compile 'com.amazonaws:aws-android-sdk-s3:2.2.+'

}

Step 2:

We must remember add the internet read and write permission in  AndroidManifest.xml.

<!-- app/AndroidManifest.xml -->

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

<uses-permission android:name="android.permission.INTERNET" />

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

...

</manifest>

** Read and write permission as made run time permission in marshmallow devices  so don’t  forget to add the the permission in the code while accessing the Gallery and here is the link to add the run time permission

Step 4:

Get the path of the selected image as you select the image or capture the image and below code helps you to select the image and fetch the path

private void SelectImage() {
    final CharSequence[] options = { "Capture image", "Select from gallery" };

    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    builder.setTitle("Select");
    builder.setCancelable(true);
    builder.setItems(options, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int item) {
            if (options[item].equals("Capture image"))
            {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                File f = new File(android.os.Environment.getExternalStorageDirectory(), "newTest.jpg");
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
                startActivityForResult(intent, 1);
            }
            else if (options[item].equals("Select from gallery"))
            {
                Intent intent = new   Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, 2);

            }

        }
    });
    builder.show();
}

And in activity result you can fetch the image data and from that you can get the image path.

Step 3:

The code below will help you to upload the image selected from the gallery or camera as you pass the path of the image to the below function the below code will explain how to add the credentials to the “AWS” client .

private void uploadImageToAWS(String selectedImagePath){ 
      
   if (selectedImagePath == null) {
           Toast.makeText(this, "Could not find the filepath of 
            the selected file", Toast.LENGTH_LONG).show();
       // to make sure that file is not emapty or null 
               return;  
     } 
  
  File  file = new File(selectedImagePath);     
  AmazonS3 s3Client = null;
  if (s3Client == null) {  
  ClientConfiguration clientConfig = new ClientConfiguration();   clientConfig.setProtocol(Protocol.HTTP);   clientConfig.setMaxErrorRetry(0);   clientConfig.setSocketTimeout(60000);

  BasicAWSCredentials credentials = new BasicAWSCredentials
  (AWS_KEY,AWS_SECRET);// Add the access key and access key id to the  credentials
   
  s3Client = new AmazonS3Client(credentials, clientConfig);   s3Client.setRegion(Region.getRegion(Regions.AP_SOUTHEAST_1)); 
}

The function continues  as the  we have to pass the  stream data of the image to the “AWS” client as the object metadata to the particular bucket path in the “AWS” server which is in specified location.

stream = new FileInputStream(file);

            ObjectMetadata objectMetadata = new ObjectMetadata();

            Log.d("messge", "converting to bytes");

            objectMetadata.setContentLength(file.length());

            String[] s = selectedImagePath.split(".");

            String extenstion = s[s.length - 1];

            Log.d("messge", "set content length : " + file.length() + "sss" + extenstion);

            String fileName = UUID.randomUUID().toString();

            PutObjectRequest putObjectRequest = new PutObjectRequest(AWS_BUCKET, "new/" + fileName + "." + extenstion, stream, objectMetadata)

                    .withCannedAcl(CannedAccessControlList.PublicRead);

// above line is  making the request to the aws  server for the specific place to upload the image were aws_bucket is the main folder  name and inside that is the profiles folder and there the file will be get uploaded

            PutObjectResult result = s3Client.putObject(putObjectRequest);

“https://s3-ap-southeast-1.amazonaws.com/xchange-web/profiles/”+fileName+”.”+extenstion. //Will be your uploaded image url from the AWS.

And final result will look like this.

Download the code from here.

6 thoughts on “Upload images to the AWS from android

  1. Appreciating the time and effort you put into your blog and detailed information you present.
    It’s awesome to come across a blog every once
    in a while that isn’t the same out of date rehashed information. Wonderful
    read! I’ve saved your site and I’m adding your RSS
    feeds to my Google account.

  2. Excellent post. I was checking continuously this blog and I
    am impressed! Extremely useful information particularly the last part :
    ) I care for such information a lot. I was seeking this certain info for
    a long time. Thank you and best of luck.

  3. Hi there just wanted to give you a quick heads up. The text in your article seem to be running off the screen in Internet explorer.
    I’m not sure if this is a formatting issue or something to do with web browser compatibility
    but I figured I’d post to let you know. The design and style
    look great though! Hope you get the issue resolved soon. Many thanks

  4. With havin so much content do you ever run into any problems of
    plagorism or copyright violation? My site has a lot of completely unique content I’ve either authored myself or
    outsourced but it seems a lot of it is popping it up all over
    the web without my agreement. Do you know any methods to help protect against content from being stolen? I’d genuinely appreciate it.

  5. I’m really enjoying the design andd layout of your
    blog. It’s a very easy on the eyws which makes it much more pleasant
    for me to come here andd visit more often. Did you hire out a designer
    to create your theme? Fantastic work!

  6. I just like the helpful information you supply in your articles. I’ll bookmark your weblog and test again right here frequently. I’m relatively certain I’ll be told a lot of new stuff proper right here! Good luck for the following!

Leave a Reply

Your email address will not be published. Required fields are marked *