This method returns the extension of the file (jpg, png, pdf, epub etc..).
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;
}
I will parrot the answer of Bhavesh with Kotlin extension and return type of okhttp3.MediaType:
fun Uri.mimeType(contentResolver: ContentResolver)
: MediaType? {
if (scheme.equals(ContentResolver.SCHEME_CONTENT)) {
// get (image/jpeg, video/mp4) from ContentResolver if uri scheme is "content://"
return contentResolver.getType(this)?.toMediaTypeOrNull()
} else {
// get (.jpeg, .mp4) from uri "file://example/example.mp4"
val fileExtension = MimeTypeMap.getFileExtensionFromUrl(toString())
// turn ".mp4" into "video/mp4"
return MimeTypeMap.getSingleton()
.getMimeTypeFromExtension(fileExtension.toLowerCase(Locale.US))
?.toMediaTypeOrNull()
}
}