从图库中选择图像后,我想用retrofit2 上传它。
https://futurestud.io/blog/retrofit-2-how-to-upload-files-to-server
为此,我必须获取真实的文件路径。
allImgUris.get(0)给了我:
content://com.android.providers.downloads.documents/document/5
allImgUris.get(0).getPath()给了我:
/document/5
我需要将真实文件路径传递给:
File file = new File(allImgUris.get(0));
我发现了很多关于处理上下文和游标的函数的所谓“好”答案,但它们都不起作用。
知道如何解决这个问题吗?
看起来很微不足道,但结果却浪费了数小时的研究时间。
任何帮助将不胜感激!
不工作:
Cursor cursor = getApplicationContext().getContentResolver().query(allImgUris.get(0), null, null, null, null);
if (cursor == null) {
selectedImagePath = allImgUris.get(0).getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
selectedImagePath = cursor.getString(idx); // ava.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
cursor.close();
}
给出:
Java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
也不工作:
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.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();
}
}
}
String selectedImagePath = getRealPathFromURI(getApplicationContext(),allImgUris.get(0) );
返回空