Android Aws Upload Bitmap Object to S3 Transferutility
Amazon Simple Storage Service (Amazon S3) is object storage built to store and retrieve any amount of information from web or mobile. Amazon S3 is designed to make web-calibration computing easier for developers. In this tutorial, we're gonna create an Android App that tin can upload/download files (images) to/from Amazon S3.
Related Postal service: How to integrate AWS Mobile SDK into Android App
I. Technology
– Android Studio 2.ten
– AWS Mobile SDK Client 2.six.7
II. Data Storage with Amazon S3
1. Integrate AWS Mobile SDK into Android App
Please visit this article for details.
2. Enable User Data Storage
Open your project in Mobile Hub and choose the User Information Storage tile to enable the feature.
Choose Shop user information and click on Salvage push:
3. Updated latest cloud configuration file
Return to the projection details page, click on Integrate push:
Download new Cloud Config file, and then override it in <projection>/app/src/primary/res/raw:
iv. Create an IAM user
We demand to provide admission permission mobile bucket. Then follow these step to create an IAM user and go Access fundamental ID and Secret access key:
Go to https://console.aws.amazon.com/iam/
In the navigation pane, choose Users and then choose Add user.
Input User proper name, choose Programmatic access for Access type:
Press Next: Permissions button -> become to Set permissions for jsa-user screen.
Now, choose Attach existing policies directly -> filter policy blazon s3, then cheque AmazonS3FullAccess:
Printing Next: Review:
Press Create user:
Press Download .csv for {Access fundamental ID, Secret access key}.
v. Connect to Amazon S3
v.1 Add dependencies
Open app/build.gradle, add:
dependencies { ... implementation ('com.amazonaws:aws-android-sdk-mobile-client:2.half-dozen.vii@aar') { transitive = truthful } implementation 'com.amazonaws:aws-android-sdk-s3:2.6.+' implementation 'com.amazonaws:aws-android-sdk-cognito:2.half dozen.+' } five.2 Add TransferService
Open up AndroidManifest.xml, add service and set permission for read/write file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.javasampleapproach.s3amazon"> <application ...> ... <activity android:proper name=".MainActivity"> ... </activity> <service android:name="com.amazonaws.mobileconnectors.s3.transferutility.TransferService" android:enabled="true" /> </application> <uses-permission android:proper noun="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> </manifest> v.3 Plant connection with AWS Mobile
AWSMobileClient is a singleton that will exist an interface for AWS services. In onCreate() method, initialize information technology:
import com.amazonaws.services.s3.AmazonS3Client; public form MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); AWSMobileClient.getInstance().initialize(this).execute(); } five.4 Upload a File
// KEY and Cloak-and-dagger are gotten when we create an IAM user above BasicAWSCredentials credentials = new BasicAWSCredentials(KEY, SECRET); AmazonS3Client s3Client = new AmazonS3Client(credentials); TransferUtility transferUtility = TransferUtility.builder() .context(getApplicationContext()) .awsConfiguration(AWSMobileClient.getInstance().getConfiguration()) .s3Client(s3Client) .build(); // "jsaS3" will be the folder that contains the file TransferObserver uploadObserver = transferUtility.upload("jsaS3/" + fileName, file); uploadObserver.setTransferListener(new TransferListener() { @Override public void onStateChanged(int id, TransferState state) { if (TransferState.COMPLETED == state) { // Handle a completed download. } } @Override public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) { float percentDonef = ((float)bytesCurrent/(float)bytesTotal) * 100; int percentDone = (int)percentDonef; } @Override public void onError(int id, Exception ex) { // Handle errors } }); // If your upload does not trigger the onStateChanged method inside your // TransferListener, y'all tin can directly check the transfer country every bit shown hither. if (TransferState.COMPLETED == uploadObserver.getState()) { // Handle a completed upload. } 5.5 Download a File
// KEY and Undercover are gotten when nosotros create an IAM user above BasicAWSCredentials credentials = new BasicAWSCredentials(Key, Undercover); AmazonS3Client s3Client = new AmazonS3Client(credentials); TransferUtility transferUtility = TransferUtility.builder() .context(getApplicationContext()) .awsConfiguration(AWSMobileClient.getInstance().getConfiguration()) .s3Client(s3Client) .build(); TransferObserver downloadObserver = transferUtility.download("jsaS3/" + fileName, localFile); downloadObserver.setTransferListener(new TransferListener() { @Override public void onStateChanged(int id, TransferState country) { if (TransferState.COMPLETED == state) { // Handle a completed upload. } } @Override public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) { float percentDonef = ((bladder)bytesCurrent/(float)bytesTotal) * 100; int percentDone = (int)percentDonef; } @Override public void onError(int id, Exception ex) { // Handle errors } }); Three. Practice
1. Fix Projection
Follow instruction above to:
– Integrate AWS Mobile SDK into Android App
– Enable User Information Storage
– Updated latest deject configuration file
– Create an IAM user and get {Admission central ID, Secret access key}
Project Construction:
2. Dependencies
Open app/build.gradle, add:
dependencies { ... implementation ('com.amazonaws:aws-android-sdk-mobile-client:2.half dozen.7@aar') { transitive = true } implementation 'com.amazonaws:aws-android-sdk-s3:2.half dozen.+' implementation 'com.amazonaws:aws-android-sdk-cognito:2.half-dozen.+' } three. AndroidManifest.xml
Open AndroidManifest.xml, add service and set permission for network, read/write file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.javasampleapproach.s3amazon"> <application ...> ... <activity android:name=".MainActivity"> ... </activeness> <service android:name="com.amazonaws.mobileconnectors.s3.transferutility.TransferService" android:enabled="truthful" /> </application> <uses-permission android:proper name="android.permission.Net" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> </manifest> four. Layout
<?xml version="one.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:paddingLeft="16dp" android:paddingRight="16dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="ozenero.com" android:textSize="20sp" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:weightSum="3"> <Button android:id="@+id/btn_choose_file" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="Cull File" /> <EditText android:id="@+id/edt_file_name" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="2" android:hint="File Proper noun" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:weightSum="two"> <Button android:id="@+id/btn_upload" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="Upload" /> <Button android:id="@+id/btn_download" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="Download" /> </LinearLayout> <TextView android:id="@+id/tv_file_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_margin="5dp" android:text="File Name" /> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:weightSum="5"> <ImageView android:id="@+id/img_file" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="4.7" /> </LinearLayout> </LinearLayout> 5. Primary Lawmaking
MainActivity.java
bundle com.javasampleapproach.s3amazon; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.bone.Environment; import android.provider.MediaStore; import android.back up.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.webkit.MimeTypeMap; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.mobile.client.AWSMobileClient; 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.services.s3.AmazonS3Client; import com.amazonaws.util.IOUtils; import coffee.io.File; import coffee.io.FileOutputStream; import java.io.IOException; import coffee.io.InputStream; import java.io.OutputStream; public form MainActivity extends AppCompatActivity implements View.OnClickListener { private final String Key = "xxx"; private terminal String SECRET = "xxxxxx"; private AmazonS3Client s3Client; private BasicAWSCredentials credentials; //track Choosing Prototype Intent private static final int CHOOSING_IMAGE_REQUEST = 1234; private TextView tvFileName; private ImageView imageView; individual EditText edtFileName; private Uri fileUri; private Bitmap bitmap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageView = findViewById(R.id.img_file); edtFileName = findViewById(R.id.edt_file_name); tvFileName = findViewById(R.id.tv_file_name); tvFileName.setText(""); findViewById(R.id.btn_choose_file).setOnClickListener(this); findViewById(R.id.btn_upload).setOnClickListener(this); findViewById(R.id.btn_download).setOnClickListener(this); AWSMobileClient.getInstance().initialize(this).execute(); credentials = new BasicAWSCredentials(KEY, SECRET); s3Client = new AmazonS3Client(credentials); } private void uploadFile() { if (fileUri != naught) { final String fileName = edtFileName.getText().toString(); if (!validateInputFileName(fileName)) { return; } concluding File file = new File(Surroundings.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "/" + fileName); createFile(getApplicationContext(), fileUri, file); TransferUtility transferUtility = TransferUtility.builder() .context(getApplicationContext()) .awsConfiguration(AWSMobileClient.getInstance().getConfiguration()) .s3Client(s3Client) .build(); TransferObserver uploadObserver = transferUtility.upload("jsaS3/" + fileName + "." + getFileExtension(fileUri), file); uploadObserver.setTransferListener(new TransferListener() { @Override public void onStateChanged(int id, TransferState land) { if (TransferState.COMPLETED == state) { Toast.makeText(getApplicationContext(), "Upload Completed!", Toast.LENGTH_SHORT).show(); file.delete(); } else if (TransferState.FAILED == state) { file.delete(); } } @Override public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) { bladder percentDonef = ((float) bytesCurrent / (bladder) bytesTotal) * 100; int percentDone = (int) percentDonef; tvFileName.setText("ID:" + id + "|bytesCurrent: " + bytesCurrent + "|bytesTotal: " + bytesTotal + "|" + percentDone + "%"); } @Override public void onError(int id, Exception ex) { ex.printStackTrace(); } }); } } private void downloadFile() { if (fileUri != null) { terminal Cord fileName = edtFileName.getText().toString(); if (!validateInputFileName(fileName)) { return; } endeavour { final File localFile = File.createTempFile("images", getFileExtension(fileUri)); TransferUtility transferUtility = TransferUtility.builder() .context(getApplicationContext()) .awsConfiguration(AWSMobileClient.getInstance().getConfiguration()) .s3Client(s3Client) .build(); TransferObserver downloadObserver = transferUtility.download("jsaS3/" + fileName + "." + getFileExtension(fileUri), localFile); downloadObserver.setTransferListener(new TransferListener() { @Override public void onStateChanged(int id, TransferState country) { if (TransferState.COMPLETED == country) { Toast.makeText(getApplicationContext(), "Download Completed!", Toast.LENGTH_SHORT).show(); tvFileName.setText(fileName + "." + getFileExtension(fileUri)); Bitmap bmp = BitmapFactory.decodeFile(localFile.getAbsolutePath()); imageView.setImageBitmap(bmp); } } @Override public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) { float percentDonef = ((bladder) bytesCurrent / (float) bytesTotal) * 100; int percentDone = (int) percentDonef; tvFileName.setText("ID:" + id + "|bytesCurrent: " + bytesCurrent + "|bytesTotal: " + bytesTotal + "|" + percentDone + "%"); } @Override public void onError(int id, Exception ex) { ex.printStackTrace(); } }); } take hold of (IOException e) { due east.printStackTrace(); } } else { Toast.makeText(this, "Upload file before downloading", Toast.LENGTH_LONG).show(); } } @Override public void onClick(View view) { int i = view.getId(); if (i == R.id.btn_choose_file) { showChoosingFile(); } else if (i == R.id.btn_upload) { uploadFile(); } else if (i == R.id.btn_download) { downloadFile(); } } private void showChoosingFile() { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Image"), CHOOSING_IMAGE_REQUEST); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent information) { super.onActivityResult(requestCode, resultCode, data); if (bitmap != null) { bitmap.recycle(); } if (requestCode == CHOOSING_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != nothing) { fileUri = data.getData(); try { bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), fileUri); } take hold of (IOException east) { e.printStackTrace(); } } } private String getFileExtension(Uri uri) { ContentResolver contentResolver = getContentResolver(); MimeTypeMap mime = MimeTypeMap.getSingleton(); return mime.getExtensionFromMimeType(contentResolver.getType(uri)); } private boolean validateInputFileName(String fileName) { if (TextUtils.isEmpty(fileName)) { Toast.makeText(this, "Enter file name!", Toast.LENGTH_SHORT).show(); return simulated; } return truthful; } individual void createFile(Context context, Uri srcUri, File dstFile) { attempt { InputStream inputStream = context.getContentResolver().openInputStream(srcUri); if (inputStream == nil) return; OutputStream outputStream = new FileOutputStream(dstFile); IOUtils.copy(inputStream, outputStream); inputStream.close(); outputStream.close(); } catch (IOException e) { eastward.printStackTrace(); } } } 6. Check Results
Run the Android App, click on Cull FILE push button, select image file and set file name in the blank. And then check UPLOAD and DOWNLOAD.
Go to https://console.aws.amazon.com/s3/buckets/, click on 30-userfiles-mobilehub-thirty saucepan (which is automatically generated when we enable User Data Storage:
Nosotros will run across jsaS3 folder:
And our files have been uploaded:
Four. Sourcecode
S3Amazon
Source: https://ozenero.com/uploaddownload-files-images-amazon-s3-android
0 Response to "Android Aws Upload Bitmap Object to S3 Transferutility"
Post a Comment