从图库中选择图像后,我想用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) );
返回null
答案 0 :(得分:0)
显然要走的路是获取位图并再次将其保存到文件系统并以此方式检索路径。
Saving and Reading Bitmaps/Images from Internal memory in Android