Suppose I have a full path of file like:(/sdcard/tlogo.png). I want to know its mime type.
I created a function for it
public static String getMimeType(File file, Context context)
{
Uri uri = Uri.fromFile(file);
ContentResolver cR = context.getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
String type = mime.getExtensionFromMimeType(cR.getType(uri));
return type;
}
but when i call it, it returns null.
File file = new File(filePath);
String fileType=CommonFunctions.getMimeType(file, context);
I tryed to use standart methods to determine mime type, but I cannot retain file extension using MimeTypeMap.getFileExtensionFromUrl(uri.getPath()). This method returned me an empty String. So I made non-trivial solution to retain file extention.
Here is method returning file extention
And having retained file extention it is possible to get mime type like below
Here is the solution which I used in my Android app:
you have multiple choice to get extension of file:like: 1-
String filename = uri.getLastPathSegment();
see this link2-you can use this code also
but this not good aproch. 3-if you have URI of file then use this Code
4-if you have URL then use this code:
enjoy your code:)
mime from local file:
Pay super close attention to umerk44's solution above.
getMimeTypeFromExtension
invokesguessMimeTypeTypeFromExtension
and is CASE SENSITIVE. I spent an afternoon on this then took a closer look -getMimeTypeFromExtension
will returnNULL
if you pass it "JPG" whereas it will return "image/jpeg" if you pass it "jpg".