我需要上传图像到AWS s3桶在安卓。我实现了用户已经从图库中拍摄了一张照片,之后有了图像路径,我需要将其保存在bucket中,并在Android中从bucket中获取url。
我有访问密钥、秘密密钥和桶名。我不清楚如何在Android中实现这一点。请帮帮我。
//这是从画廊拍一张照片的代码
private void selectImage() {
final CharSequence[] options = {"Choose from Gallery", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Upload Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Choose from Gallery")) {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
@SuppressLint("LongLogTag")
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor c = this.getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
thumbnail = getResizedBitmap(thumbnail, 400);
Log.w("path of image from gallery......******************.........", picturePath + "");
imageView.setImageBitmap(thumbnail);
BitMapToString(thumbnail);
}
}
}
private void BitMapToString(Bitmap userImage1) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
userImage1.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
Document_img1 = Base64.encodeToString(b, Base64.DEFAULT);
System.out.println(Document_img1 + "........IMAGE");
}
private Bitmap getResizedBitmap(Bitmap image, int maxSize) {
int width = image.getWidth();
int height = image.getHeight();
float bitmapRatio = (float) width / (float) height;
if (bitmapRatio > 1) {
width = maxSize;
height = (int) (width / bitmapRatio);
} else {
height = maxSize;
width = (int) (height * bitmapRatio);
}
return Bitmap.createScaledBitmap(image, width, height, true);
}
请查看AWS放大器库中的存储类别。
有一些设置/配置要做(如该指南所述),但实际上载将如下所示:
Amplify.Storage.uploadFile(
"remoteS3Key",
localFile,
result -> Log.i("Demo", "Successfully uploaded: " + result.getKey()),
failure -> Log.e("Demo", "Upload failed", failure)
);