【问题标题】:Get the real filepath of any file in Android获取Android中任何文件的真实文件路径
【发布时间】:2026-01-05 07:00:01
【问题描述】:

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

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”。

【问题讨论】:

  • 喜欢我可以给你的音频和视频对你来说好吗
  • 它需要能够处理任何类型的文件,例如图像/音频/视频 pdf docx 等...
  • 你得到的错误是什么? MediaStore 中的任何 .DATA 也只是 "_data",因为它们都继承自 MediaColumns - 这不应该是你的问题
  • 你是对的,这不是导致应用程序崩溃的原因,而是它没有从 uri 获取文件路径:文件路径返回空值

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


【解决方案1】:

原来问题是处理包含 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;

【讨论】:

    【解决方案2】:
    Uri fileUri=Uri.fromfile(fileObject);
    
    USE: setUrl(Uri.decode(fileUri));
    

    【讨论】: