Uploading images from gallery to S3 AWS android

Viewed 832

I really tried all the links before asking here. I don't know what to do, I googled everything and tried many different ways and nothing is working.

I think the problem is in the file string path. Here is my Main code:

package com.android.dji.eaglei;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.amazonaws.auth.CognitoCachingCredentialsProvider;
import com.amazonaws.mobileconnectors.s3.transferutility.TransferListener;
import com.amazonaws.mobileconnectors.s3.transferutility.TransferObserver;
import com.amazonaws.mobileconnectors.s3.transferutility.TransferState;
import com.amazonaws.mobileconnectors.s3.transferutility.TransferUtility;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.Tag;

import java.io.File;

public class MainActivity extends AppCompatActivity {

    //for image upload
    private ImageView imageView;
    private Button button;
    private static final int PICK_IMAGE = 1;
    private Uri imageUri;
    String imageName = "newTest.jpg";
    private Button upload;
    //

    // for aws
    String bucket = "eagleibucket";
    File fileToUpload ;
    AmazonS3 s3;
    TransferUtility transferUtility;
    //
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // callback method to call credentialsProvider method.
        credentialsProvider();
        // callback method to call the setTransferUtility method
        setTransferUtility();

        //uploading image
        imageView = (ImageView) findViewById(R.id.imageView);
        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openGallery();
            }
        });
        upload = (Button) findViewById(R.id.upload);
        upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setTransferUtility();
                setFileToUpload(v);
            }
        });
    }
    protected  void  openGallery(){
        Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(gallery,PICK_IMAGE);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            if (resultCode == RESULT_OK && requestCode == PICK_IMAGE) {
                imageUri = data.getData();
                imageView.setImageURI(imageUri);
                // aws uri img to upload
                imageName = (String) imageView.getTag();
                imageUri = data.getData();
                imageView.setImageURI(imageUri);




            } else {
                Toast.makeText(this, "You haven't picked an image", Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            Toast.makeText(this, "Something went wrong!", Toast.LENGTH_LONG).show();
        }
    }
    public void credentialsProvider(){

        // Initialize the Amazon Cognito credentials provider
        CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(
                getApplicationContext(),
                "us-west-2:edb44a70-b31e-44b0-b8c7-2d38a9c7c98f", // Identity pool ID
                Regions.US_WEST_2 // Region
        );
        setAmazonS3Client(credentialsProvider);
    }
    /**
     *  Create a AmazonS3Client constructor and pass the credentialsProvider.
     * @param credentialsProvider
     */
    public void setAmazonS3Client(CognitoCachingCredentialsProvider credentialsProvider){
        // Create an S3 client
        s3 = new AmazonS3Client(credentialsProvider);
        // Set the region of your S3 bucket
        s3.setRegion(Region.getRegion(Regions.US_WEST_2));
    }
    public void setTransferUtility(){
        transferUtility = new TransferUtility(s3, getApplicationContext());
    }
    /**
     * This method is used to upload the file to S3 by using TransferUtility class
     * @param view
     */
    public void setFileToUpload(View view){
        fileToUpload = new File(getRealPathFromURI(imageUri));
        if (fileToUpload == 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;
        }
        TransferObserver transferObserver = transferUtility.upload(
                bucket,
                imageName,
                fileToUpload
        );
        transferObserverListener(transferObserver);
    }
    /**
     * This is listener method of the TransferObserver
     * Within this listener method, we get status of uploading and downloading file,
     * to display percentage of the part of file to be uploaded or downloaded to S3
     * It displays an error, when there is a problem in  uploading or downloading file to or from S3.
     * @param transferObserver
     */
    public void transferObserverListener(TransferObserver transferObserver){
        transferObserver.setTransferListener(new TransferListener(){
            @Override
            public void onStateChanged(int id, TransferState state) {
                Toast.makeText(getApplicationContext(), "State Change" + state,
                        Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {
                int percentage = (int) (bytesCurrent/bytesTotal * 100);
                Toast.makeText(getApplicationContext(), "Progress in %" + percentage,
                        Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onError(int id, Exception ex) {
                Log.e("error","error");
            }
        });
    }
    private String getRealPathFromURI(Uri contentURI) {
        String thePath = "no-path-found";
        String[] filePathColumn = {MediaStore.Images.Media.DISPLAY_NAME};
        Cursor cursor = getContentResolver().query(contentURI, filePathColumn, null, null, null);
        if(cursor.moveToFirst()){
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            thePath = cursor.getString(columnIndex);
        }
        cursor.close();
        return  thePath;
    }
}

Manifest: I added the permissions as well as the service. I also added the needed libraries.

This is the Error:

E/AndroidRuntime: FATAL EXCEPTION: main Process: com.android.dji.eaglei, PID: 
        java.lang.IllegalArgumentException: Invalid file: 
            at com.amazonaws.mobileconnectors.s3.transferutility.TransferUtility.upload(TransferUtility.java:478)
            at com.amazonaws.mobileconnectors.s3.transferutility.TransferUtility.upload(TransferUtility.java:443)
            at com.amazonaws.mobileconnectors.s3.transferutility.TransferUtility.upload(TransferUtility.java:412)
            at com.amazonaws.mobileconnectors.s3.transferutility.TransferUtility.upload(TransferUtility.java:353)
            at com.android.dji.eaglei.MainActivity.setFileToUpload(MainActivity.java:134)
            at com.android.dji.eaglei.MainActivity$2.onClick(MainActivity.java:70)
            at android.view.View.performClick(View.java:5716)
            at android.widget.TextView.performClick(TextView.java:10926)
            at android.view.View$PerformClick.run(View.java:22596)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:148)
            at android.app.ActivityThread.main(ActivityThread.java:7331)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

Thanks for the help!

1 Answers

I think the file path you tried to upload was empty (because nothing written near the error ). try to exchange fileToUpload with the path of the file,or even path of another file ,just for the check. when you'll succeed with it,you can try your file and try to see what is the value of fileToUpload in "transferUtility.upload" during the run of the app.

Related