[android] 我如何獲得具有其Uri的文件的mime類型?


1 Answers

此方法返回文件的擴展名(jpg,png,pdf,epub等..)。

 public static String getMimeType(Context context, Uri uri) {
    String extension;

    //Check uri format to avoid null
    if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
        //If scheme is a content
        final MimeTypeMap mime = MimeTypeMap.getSingleton();
        extension = mime.getExtensionFromMimeType(context.getContentResolver().getType(uri));
    } else {
        //If scheme is a File
        //This will replace white spaces with %20 and also other special characters. This will avoid returning null values on file name with spaces and special characters.
        extension = MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(new File(uri.getPath())).toString());

    }

    return extension;
}
Question

我有一個用畫廊和相機獲得的Uris列表。 這些Uris是這樣的: content://media/external/images/media/94 。 我怎麼能得到它的mime類型?




對於Content Uri

ContentResolver cr = context.getContentResolver();
mimeType = cr.getType(contentUri);

for File Uri

String fileExtension = MimeTypeMap.getFileExtensionFromUrl(fileUri
            .toString());
mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
            fileExtension.toLowerCase());

for Both,適用於ContentFile

public String getMimeType(Context context, Uri uri) {
    String mimeType = null;
    if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
        ContentResolver cr = context.getContentResolver();
        mimeType = cr.getType(uri);
    } else {
        String fileExtension = MimeTypeMap.getFileExtensionFromUrl(uri
                .toString());
        mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
                fileExtension.toLowerCase());
    }
    return mimeType;
}



Related