获取Android中任何文件的真实文件路径

时间:2013-12-04 08:39:01

标签: java android android-intent filepath android-file

我有一个应用程序,我可以从设备库中选择一个图像。我需要获取文件的真实文件路径以将文件上载到远程服务器。我只使用图像成功工作,但我希望扩展我的应用程序以包含任何文件类型。尝试获取非图像的文件路径时,我当前的代码失败。到目前为止我的代码:

String filepath = "";
try {
  String[] projection = { MediaStore.Images.Media.DATA };
  Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
  if (cursor != null && cursor.getCount() != 0) {
    int column_index = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    filepath = cursor.getString(column_index);
  }
}
catch(Exception e) {
  Log.e("Path Error",e.toString());
}

我相信我的问题在于“MediaStore.Images.Media.DATA”,但我不知道如何替换它以处理所有文件类型。

更新

好的,确定我的代码是99%罚款。它适用于多种文件类型。问题是文件名包含空格。我该如何处理呢我注意到文件路径是url编码的,即空格被替换为“%20”。

2 个答案:

答案 0 :(得分:4)

原来问题是处理包含URL编码空格的文件名,即“%20”

对于任何感兴趣的人,我的改编代码如下:

String filepath = "";
String uriPath = uri.toString();

// Handle local file and remove url encoding
if(uriPath.startsWith("file://")) {
  filepath = uriPath.replace("file://","");
  try {
    return URLDecoder.decode(filepath, "UTF-8");
  } 
  catch (UnsupportedEncodingException e) {
    e.printStackTrace()
  }
}

try {
  String[] projection = { MediaStore.Images.Media.DATA };
  Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
  if (cursor != null && cursor.getCount() != 0) {
    int column_index = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    filepath = cursor.getString(column_index);
  }
}
catch(Exception e) {
  Log.e("Path Error",e.toString());
}
return filepath;

答案 1 :(得分:1)

Uri fileUri=Uri.fromfile(fileObject);

USE: setUrl(Uri.decode(fileUri));