Download Multiple Files Amazon S3 Android Transferutility
Amazon Uncomplicated Storage Service (Amazon S3) is object storage congenital to store and retrieve whatever corporeality of data from spider web or mobile. Amazon S3 is designed to make spider web-calibration computing easier for developers. In this tutorial, we're gonna create an Android App that 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.x
– AWS Mobile SDK Customer two.6.vii
2. Data Storage with Amazon S3
1. Integrate AWS Mobile SDK into Android App
Please visit this article for details.
2. Enable User Information Storage
Open your project in Mobile Hub and choose the User Data Storage tile to enable the feature.
Cull Shop user data and click on Save button:
3. Updated latest cloud configuration file
Render to the project details page, click on Integrate push button:
Download new Cloud Config file, and so override it in <project>/app/src/chief/res/raw:
iv. Create an IAM user
We need to provide access permission mobile bucket. And so follow these footstep to create an IAM user and get Access cardinal ID and Secret access fundamental:
Go to https://console.aws.amazon.com/iam/
In the navigation pane, choose Users and then cull Add together user.
Input User name, choose Programmatic admission for Admission blazon:
Press Next: Permissions button -> go to Set permissions for jsa-user screen.
Now, choose Attach existing policies direct -> filter policy blazon s3, then check AmazonS3FullAccess:
Press Next: Review:
Press Create user:
Press Download .csv for {Admission key ID, Secret access primal}.
5. Connect to Amazon S3
5.1 Add together dependencies
Open app/build.gradle, add:
dependencies { ... implementation ('com.amazonaws:aws-android-sdk-mobile-client:2.6.7@aar') { transitive = true } implementation 'com.amazonaws:aws-android-sdk-s3:2.6.+' implementation 'com.amazonaws:aws-android-sdk-cognito:2.vi.+' }
v.two Add together TransferService
Open up AndroidManifest.xml, add service
and ready permission for read/write file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.javasampleapproach.s3amazon"> <awarding ...> ... <activity android:proper noun=".MainActivity"> ... </activity> <service android:name="com.amazonaws.mobileconnectors.s3.transferutility.TransferService" android:enabled="true" /> </awarding> <uses-permission android:name="android.permission.Internet" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:proper noun="android.permission.READ_EXTERNAL_STORAGE" /> </manifest>
5.3 Establish connection with AWS Mobile
AWSMobileClient
is a singleton that volition exist an interface for AWS services. In onCreate()
method, initialize information technology:
import com.amazonaws.services.s3.AmazonS3Client; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); AWSMobileClient.getInstance().initialize(this).execute(); }
5.4 Upload a File
// Key and Cloak-and-dagger are gotten when we create an IAM user in a higher place BasicAWSCredentials credentials = new BasicAWSCredentials(KEY, Clandestine); AmazonS3Client s3Client = new AmazonS3Client(credentials); TransferUtility transferUtility = TransferUtility.builder() .context(getApplicationContext()) .awsConfiguration(AWSMobileClient.getInstance().getConfiguration()) .s3Client(s3Client) .build(); // "jsaS3" volition 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 country) { 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, you lot can directly check the transfer state as shown here. if (TransferState.COMPLETED == uploadObserver.getState()) { // Handle a completed upload. }
5.v Download a File
// Fundamental and SECRET are gotten when nosotros create an IAM user above BasicAWSCredentials credentials = new BasicAWSCredentials(KEY, Hush-hush); 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 state) { if (TransferState.COMPLETED == state) { // Handle a completed upload. } } @Override public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) { bladder percentDonef = ((float)bytesCurrent/(float)bytesTotal) * 100; int percentDone = (int)percentDonef; } @Override public void onError(int id, Exception ex) { // Handle errors } });
Three. Exercise
ane. Ready Project
Follow education in a higher place to:
– Integrate AWS Mobile SDK into Android App
– Enable User Information Storage
– Updated latest cloud configuration file
– Create an IAM user and get {Admission fundamental ID, Hugger-mugger access key}
Projection Structure:
ii. Dependencies
Open app/build.gradle, add:
dependencies { ... implementation ('com.amazonaws:aws-android-sdk-mobile-client:2.6.7@aar') { transitive = true } implementation 'com.amazonaws:aws-android-sdk-s3:2.six.+' implementation 'com.amazonaws:aws-android-sdk-cognito:2.6.+' }
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" bundle="com.javasampleapproach.s3amazon"> <awarding ...> ... <activeness android:name=".MainActivity"> ... </activity> <service android:name="com.amazonaws.mobileconnectors.s3.transferutility.TransferService" android:enabled="true" /> </application> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:proper name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:proper noun="android.permission.READ_EXTERNAL_STORAGE" /> </manifest>
4. Layout
<?xml version="i.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="iii"> <Button android:id="@+id/btn_choose_file" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="Choose File" /> <EditText android:id="@+id/edt_file_name" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="2" android:hint="File Name" /> </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="five"> <ImageView android:id="@+id/img_file" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="four.7" /> </LinearLayout> </LinearLayout>
5. Main Code
MainActivity.coffee
parcel 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.support.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.customer.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 java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public form MainActivity extends AppCompatActivity implements View.OnClickListener { private final Cord KEY = "xxx"; private concluding String Hush-hush = "xxxxxx"; private AmazonS3Client s3Client; private BasicAWSCredentials credentials; //track Choosing Image Intent private static final int CHOOSING_IMAGE_REQUEST = 1234; private TextView tvFileName; private ImageView imageView; private EditText edtFileName; individual Uri fileUri; private Bitmap bitmap; @Override protected void onCreate(Package 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(Fundamental, Hush-hush); s3Client = new AmazonS3Client(credentials); } individual void uploadFile() { if (fileUri != goose egg) { final Cord fileName = edtFileName.getText().toString(); if (!validateInputFileName(fileName)) { return; } final File file = new File(Environment.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 country) { if (TransferState.COMPLETED == land) { Toast.makeText(getApplicationContext(), "Upload Completed!", Toast.LENGTH_SHORT).show(); file.delete(); } else if (TransferState.FAILED == land) { file.delete(); } } @Override public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) { float percentDonef = ((float) 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(); } }); } } private void downloadFile() { if (fileUri != null) { final String fileName = edtFileName.getText().toString(); if (!validateInputFileName(fileName)) { return; } effort { 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 == state) { 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 = ((float) 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(); } }); } grab (IOException e) { e.printStackTrace(); } } else { Toast.makeText(this, "Upload file earlier 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 Paradigm"), CHOOSING_IMAGE_REQUEST); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (bitmap != zip) { bitmap.recycle(); } if (requestCode == CHOOSING_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) { fileUri = data.getData(); try { bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), fileUri); } catch (IOException east) { e.printStackTrace(); } } } private Cord getFileExtension(Uri uri) { ContentResolver contentResolver = getContentResolver(); MimeTypeMap mime = MimeTypeMap.getSingleton(); return mime.getExtensionFromMimeType(contentResolver.getType(uri)); } private boolean validateInputFileName(Cord fileName) { if (TextUtils.isEmpty(fileName)) { Toast.makeText(this, "Enter file name!", Toast.LENGTH_SHORT).show(); return false; } render true; } private void createFile(Context context, Uri srcUri, File dstFile) { try { InputStream inputStream = context.getContentResolver().openInputStream(srcUri); if (inputStream == cipher) return; OutputStream outputStream = new FileOutputStream(dstFile); IOUtils.copy(inputStream, outputStream); inputStream.close(); outputStream.shut(); } grab (IOException e) { e.printStackTrace(); } } }
half dozen. Check Results
Run the Android App, click on Choose FILE push, select image file and set file proper name in the blank. Then check UPLOAD and DOWNLOAD.
Become to https://panel.aws.amazon.com/s3/buckets/
, click on xxx-userfiles-mobilehub-30 saucepan (which is automatically generated when nosotros enable User Data Storage:
Nosotros will run into jsaS3 folder:
And our files take been uploaded:
IV. Sourcecode
S3Amazon
DOWNLOAD HERE
Posted by: mastrangeloefece1947.blogspot.com
0 Comentarios