108

I have a List of Uris obtained with the Gallery and the Camera. These Uris are like this: content://media/external/images/media/94. How I can get its mime type?

Brais Gabin
  • 5,827
  • 6
  • 57
  • 92

7 Answers7

221

You can try

ContentResolver cR = context.getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
String type = mime.getExtensionFromMimeType(cR.getType(uri));

Edit :

mime.getExtensionFromMimeType(cR.getType(uri)) 

returns -> "jpeg"

cR.getType(uri);

returns "image/jpeg" that is the expected value.

Kartik Domadiya
  • 29,868
  • 19
  • 93
  • 104
  • 18
    ````mime.getExtensionFromMimeType(cR.getType(uri))```` returns me ````"jpeg"```` but ````cR.getType(uri)```` returns ````"image/jpeg"```` that is the expected value. – Brais Gabin Sep 18 '12 at 14:35
  • This is not working for some devices..Is there any alternative? – Aditi Parikh Apr 20 '17 at 10:06
  • 2
    @AditiParikh [This answer](https://stackoverflow.com/a/31691791/7196681) works for me... – Curiosity Jun 21 '17 at 09:45
  • 1
    @BraisGabin I'm trying to read in a .csv file. For some reason I get "text/csv" for `cR.getType(uri)` but for `ime.getExtensionFromMimeType(cR.getType(uri));` I get null. Is .csv just not supported or something? – Justin Liu Sep 11 '17 at 05:59
  • No, it's not supported. You can see a list of the currently supported extensions in this [source code](https://android.googlesource.com/platform/libcore/+/master/luni/src/main/java/libcore/net/MimeUtils.java). – Brais Gabin Oct 12 '17 at 15:07
  • How is this the accepted answer when it uses a method that returns extension of the file while OP is asking about the mime type? – Shahood ul Hassan Oct 31 '19 at 03:43
38

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;
}
Aaron
  • 1,256
  • 11
  • 16
  • 2
    Its working for me.. I did follow https://developer.android.com/training/sharing/receive.html – Amitabha Biswas Nov 24 '16 at 09:23
  • @Aaron Thanks. It works perfectly for non-english file names. – Ghasem Sadeghi Oct 18 '19 at 20:24
  • can you explain why u need Uri.fromFile(new File(uri.getPath())) when the method params includes a Uri – DoruChidean Feb 25 '21 at 13:29
  • Because I need to parse spaces and special characters i.e space should be %20. Using new File() on the uri path will automatically parse those special characters. If you remove this part, this code will throw an error on file names that have spaces or special characters – Aaron Feb 27 '21 at 01:17
22

for 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, works for Content as well as File.

public String getMimeType(Context context, Uri uri) {
    String mimeType = null;
    if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
        ContentResolver cr = context.getContentResolver();
        mimeType = cr.getType(uri);
    } else {
        String fileExtension = MimeTypeMap.getFileExtensionFromUrl(uri
                .toString());
        mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
                fileExtension.toLowerCase());
    }
    return mimeType;
}
davsinghm
  • 5
  • 3
Bhavesh Rangani
  • 1,490
  • 12
  • 23
  • 1
    Be careful with MimeTypeMap.getFileExtensionFromUrl(), it seems not to be able to handle all filenames. For example, on my emulator, photos taken with the camera contain commas and spaces in the filename, which causes this method to return an empty String. I recommend falling back to manual parsing if the method call failed (get the index of the last '.' and use it to take the substring) – lbenedetto Apr 29 '19 at 06:13
8

Instead of this:

String type = mime.getExtensionFromMimeType(cR.getType(uri));

Do this:

String type = cR.getType(uri);

And you will get this: image/jpeg.

Tim S. Van Haren
  • 8,861
  • 2
  • 30
  • 34
Mohamed Ibrahim
  • 841
  • 11
  • 9
  • 16
    Only works for content uris (content://). Doesn't work for file uris (file://) – zyamys May 30 '16 at 19:18
  • 1
    Actually the path doesn't matter for the getType. It's simply the case that the other end of the intent needs to have explicitly set the type for the intent. Often times this doesn't happen for paths. – Tatarize Aug 22 '16 at 08:57
2

Return "image/jpeg" for example

fun Uri.getMimeType(context: Context): String? {
    return when (scheme) {
        ContentResolver.SCHEME_CONTENT -> context.contentResolver.getType(this)
        ContentResolver.SCHEME_FILE -> MimeTypeMap.getSingleton().getMimeTypeFromExtension(
            MimeTypeMap.getFileExtensionFromUrl(toString()).toLowerCase(Locale.US)
        )
        else -> null
    }
}
kulikovman
  • 333
  • 4
  • 8
0

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()
    }
}
Jemshit
  • 9,501
  • 5
  • 69
  • 106
0

for kotlin this function will work

fun getMime(uri : Uri, context: Context) : String?{
    val cr = context.contentResolver
    return cr.getType(uri)
}
Hamza Ali
  • 272
  • 4
  • 9