【发布时间】:2014-03-11 12:07:53
【问题描述】:
我打算启动一个文件选择器,用户可以在其中选择要使用的 pdf 文件并上传到服务器
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
startActivityForResult(intent,1);
当他们选择一个文件时,它会返回到onActivityResult,在那里我查看文件的Uri,看看它是否包含.pdf
if(requestCode == 1 && resultCode == RESULT_OK){
Uri filePath = data.getData();
File file = new File(filePath.getPath());
if(filePath.toString().contains(".pdf")){
if(file.length() <= 1048576){
de.setPDFUri(filePath.toString());
}else{
Toast.makeText(this,"PDF cannot be more than 1 MB, please select another", Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(this,"Can only upload PDF files", Toast.LENGTH_SHORT).show();
}
}
但这仅适用于某些文件管理器应用程序(Astro、Explorer),大多数情况下我都会得到这样的回报
file:///storage/sdcard0/Download/20131231103232738561744.pdf
在其他程序(制造商的内置应用程序是我迄今为止看到的唯一程序)上,我得到了这样的回报
content://media/external/file/109
这显然没有告诉我有关文件及其类型的任何信息,并返回该文件的 ContentProvider 信息。
有没有办法只让用户选择.pdf 文件,方法是发送意图中的内容,或者检查 uri 并确保它是 .pdf 文件?
【问题讨论】:
-
这个问题提供了一些关于如何从内容 URI 获取文件路径的想法:stackoverflow.com/questions/20067508
标签: android android-intent android-file