我在将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
发布于 2017-04-11 23:21:20
试一试,我强烈建议不要使用
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();
}
}
}发布于 2017-04-11 22:20:55
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()。请查收。
https://stackoverflow.com/questions/43348489
复制相似问题