我试图将所选文件(不是图像专用,可以是任何文件)从文件选择器意图转换为zip文件。我需要完整的文件路径来执行此操作,但意图仅提供uri路径。
这是我的代码:
public void onActivityResult(int requestCode, int resultCode, Intent result){
if(requestCode == 111) {
if(null != result) { // checking empty selection
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
if(null != result.getClipData()) { // checking multiple selection or not
for(int i = 0; i < result.getClipData().getItemCount(); i++) {
String uri = result.getClipData().getItemAt(i).getUri().getPath();
uriList.add(uri);
Log.d("PATH: ",uri);
}
confirmationDialog();
} else {
String uri = result.getData().getPath();
uriList.add(uri);
Log.d("PATH: ",uri);
confirmationDialog();
}
}else{Toast.makeText(getApplicationContext(),
"An error has occured: API level requirements not met",Toast.LENGTH_SHORT).show();};
}
}
}
它应该提供真实路径,例如:“ /sdcard/filename.example”
相反,它给了我:“ / document / 9016-4ef8:filename.example”
答案 0 :(得分:0)
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
System.out.println("picturePath +"+ picturePath ); //path of sdcard
答案 1 :(得分:0)
好吧,我通过使用内置文件浏览器之外的另一个文件浏览器修复了该问题,在我的情况下,我使用了Cx File Explorer,不同的文件浏览器返回了不同的值。
答案 2 :(得分:0)
选择/获取文件的实际路径:
val intent = Intent(Intent.ACTION_GET_CONTENT)
intent.type = "*/*"
startActivityForResult(intent, 1)
onActivityResult:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
val file = data?.data?.let {
getFileFromUri(requireContext().contentResolver, uri, requireContext().cacheDir)
}
}
}
获取文件:
private fun getFileFromUri(contentResolver: ContentResolver, uri: Uri, directory: File): File {
val file =
File.createTempFile("suffix", ".prefix", directory)
file.outputStream().use {
contentResolver.openInputStream(uri)?.copyTo(it)
}
return file
}
一旦获得文件,我们就可以获取文件的实际路径。