How can I save image to AWS S3 bucket and then retrieve the image public url and save the url into dynamodb alongside other user input data without the user leaving the activity or fragment? Can all these be achieved at once? Any sample code example will help a lot. Thanks!!
This is how I upload images to S3:
CognitoCachingCredentialsProvider credentialsProvider =
new CognitoCachingCredentialsProvider(
context.getApplicationContext(),
YOUR_IDENTITY_POOL_ID,
Regions.US_EAST_1);
AmazonS3Client s3Client = new AmazonS3Client(credentialsProvider);
TransferUtility transferUtility = new TransferUtility(s3Client, context.
getApplicationContext());
TransferObserver observer = transferUtility.upload(
MY_BUCKET, // The S3 bucket to upload to
OBJECT_KEY, // The key for the uploaded object
FILE_TO_UPLOAD // The location of the file to be uploaded );
Have this in your manifest file:
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<service android:name= "com.amazonaws.mobileconnectors.s3.transferutility.TransferService" android:enabled="true" />
Information source here
I made the folder in S3 bucket public and saved the file link in dynamoDB like this: "https://mybucket.s3.amazonaws.com/myfolder/myimage.jpg"
-
Try this code -
private void uploadImageToAWS() {
AsyncTask<String, String, String> _Task = new AsyncTask<String, String, String>() {
@Override
protected void onPreExecute() {
}
@Override
protected String doInBackground(String... arg0)
{
if (NetworkAvailablity.checkNetworkStatus(PrintRollScreenActivity.this))
{
try {
java.util.Date expiration = new java.util.Date();
long msec = expiration.getTime();
msec += 1000 * 60 * 60; // 1 hour.
expiration.setTime(msec);
publishProgress(arg0);
String existingBucketName = "YOUR_AWS_BUCKET_NAME";////////////
String keyName = "image_name";
String filePath = "";
AmazonS3Client s3Client1 = new AmazonS3Client( new BasicAWSCredentials( "AWS_KEY","AWS_SECRET") );
PutObjectRequest por = new PutObjectRequest(existingBucketName,
keyName + ".png",new File(filePath));//key is URL
//making the object Public
por.setCannedAcl(CannedAccessControlList.PublicRead);
s3Client1.putObject(por);
String _finalUrl = "https://"+existingBucketName+".s3.amazonaws.com/" + keyName + ".png";
} catch (Exception e) {
// writing error to Log
e.printStackTrace();
}
}
else
{
}
return null;
}
@Override
protected void onProgressUpdate(String... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
System.out.println("Progress : " + values);
}
@Override
protected void onPostExecute(String result)
{
}
};
_Task.execute((String[]) null);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With