Android 安卓:如何从SD卡上传图像

Android 安卓:如何从SD卡上传图像,android,Android,在我的应用程序中,我想上传SD卡上的图像,限制用户只能上传小于2mb的图像。如何才能做到这一点?使用以下步骤: 1) 使用以下意图打开图像库: Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Picture"), 101);

在我的应用程序中,我想上传SD卡上的图像,限制用户只能上传小于2mb的图像。如何才能做到这一点?

使用以下步骤:

1) 使用以下意图打开图像库:

Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 101);
2) 在
onActivityResult
func中接收所选文件的Uri

if (requestCode == 101 && data != null) {

            Uri selectedImageUri = data.getData();
} else {
            Toast toast = Toast.makeText(this, "No Image is selected.",
                    Toast.LENGTH_LONG);
            toast.show();
        }
使用以下函数将Uri转换为路径:

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);
    }
然后从路径创建一个
文件
对象,然后检查文件大小:

File mFile = new File(path);
int length = mFile.length(); // file size in bytes
之后,您只需输入
if-else
检查文件大小限制,然后使用多部分上载过程上载文件


您可以将其用于多部分上传。

如果您认为答案正确,请在答案旁边打勾。这将有助于其他用户搜索相同的问题。