【问题标题】:Get file extension of chosen file from an intent从意图中获取所选文件的文件扩展名
【发布时间】: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 文件?

【问题讨论】:

标签: android android-intent android-file


【解决方案1】:

您可以通过在 setType 函数中指定文件 MIME 类型来限制可以从 Intent 中选择的文件类型。为了限制用户只选择您可以指定的 PDF 文件:

intent.setType("application/pdf");

【讨论】:

    【解决方案2】:

    intent.setType("application/pdf");

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-24
      • 2010-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多