如何找到android映像的路径并从Uri创建文件

时间:2017-04-11 14:13:19

标签: android android-file android-contentresolver

我将Uri路径转换为URI(创建文件)时遇到问题。

我的代码是:

private void uploadImageToServer(Uri path){
    String[] filePathColumn = {MediaStore.Images.Media.DATA};

    android.database.Cursor cursor = getContentResolver().query(path, filePathColumn, null, null, null);
    if (cursor == null)
        return;

    cursor.moveToFirst();

    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
    String filePath = cursor.getString(columnIndex);
    cursor.close();

    File file = new File(filePath);
}

但是我的光标为空。

我的" Uri路径"函数的参数是: file:///storage/emulated/0/Pictures/MyApp/IMG_20170411_170952.jpg

我正在关注本教程: https://medium.com/@adinugroho/upload-image-from-android-app-using-retrofit-2-ae6f922b184c

2 个答案:

答案 0 :(得分:2)

试试这个,我强烈建议不要使用

content:// 

只需将其用作

content:

String imagePath = "";
Uri targetUri = data.getData();
        if (data.toString().contains("content:")) {
            imagePath = getRealPathFromURI(targetUri);
        } else if (data.toString().contains("file:")) {
            imagePath = targetUri.getPath();
        } else {
            imagePath = null;
        }


 public String getRealPathFromURI(Uri contentUri) {
    Cursor cursor = null;
    try {
        String[] proj = {MediaStore.Images.Media.DATA};
        cursor = getContentResolver().query(contentUri, proj, null, null,
                null);
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

答案 1 :(得分:0)

My "Uri path" parameter from function is: 
file:///storage/emulated/0/Pictures/MyApp/IMG_20170411_170952.jpg

然后您所追寻的路径是

/storage/emulated/0/Pictures/MyApp/IMG_20170411_170952.jpg

代码

private void uploadImageToServer(Uri uri){
   String filePath = uri.toString().replace("file://", "" );

   File file = new File(filePath);
}

也许你甚至可以直接使用uri.getPath()。请检查。