Android: How to Upload Images from the SD Card
In my application, I want to uplo开发者_开发问答ad the images from the SD card with restricting the user to upload only less than 2mb. How can I accomplish this?
Use following steps:
1) Use the following intent to open gallery with images:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 101);
2) Receive the Uri of selected file in onActivityResult
func.
if (requestCode == 101 && data != null) {
Uri selectedImageUri = data.getData();
} else {
Toast toast = Toast.makeText(this, "No Image is selected.",
Toast.LENGTH_LONG);
toast.show();
}
Convert the Uri into a path using following func:
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
After that create a File
object from the path and then check the size of file:
File mFile = new File(path);
int length = mFile.length(); // file size in bytes
After that you can simply put an if-else
to check the file size restriction and then use multi-part upload process for uploading the file.
you can use this article for multipart upload.
精彩评论