How to determine MIME type of file in android?
Asked Answered
I

29

222

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);
Idleman answered 21/12, 2011 at 12:13 Comment(0)
I
373

First and foremost, you should consider calling MimeTypeMap#getMimeTypeFromExtension(), like this:

// url = file path or whatever suitable URL you want.
public static String getMimeType(String url) {
    String type = null;
    String extension = MimeTypeMap.getFileExtensionFromUrl(url);
    if (extension != null) {
        type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
    }
    return type;
}
Ironlike answered 21/12, 2011 at 14:17 Comment(14)
thanks work for me and another solution of my problem is : public static String getMimeType(String path, Context context) { String extention = path.substring(path.lastIndexOf(".") ); String mimeTypeMap =MimeTypeMap.getFileExtensionFromUrl(extention); String mimeType = MimeTypeMap.getSingleton() .getMimeTypeFromExtension(mimeTypeMap); return mimeType;}Idleman
And if the file has not the good extension? a person can make a .mp3 and it contains textRipsaw
Then you'd need to actually open the file & check the magic number (depending on the format ofc) in the lead-in - this, however, also assumes that the person renaming txt-files to mp3 didn't just write ID3 in the beginning of his text to mess with you even more.Ironlike
@SushantBhatnagar you comment was helping but it need some improvment because i tried this but not working fine.Heavensent
@Diederik what about mime type with codec type, for example: video/mp4;codecs="avc1.42001E, mp4a.40.2" (MimeTypeMap.getExtensionFromMimeType()))? YouTube return mime type with codec. I must use "video/mp4;codecs...".split(";",2)[0]. FLV is not registered (mime type starts with x-, in flv: x-flv), so MimeTypeMap for x- return null. en.wikipedia.org/wiki/Internet_media_type#Unregistered_x._tree (sorry for my english)Danilodanio
this is unreliable. It is terrible to depend on file extension and determine filetype from that. I can't believe such an important thing as mentioned by @Ripsaw is being ignored.Koeppel
If file has a unknown extension. Do method return */*?Witch
GPX is not recognized either.Cycloplegia
@TimAutin, method does not work with uppercase. Try modified one: https://mcmap.net/q/76719/-how-to-determine-mime-type-of-file-in-androidColeslaw
If your have file path as /storage/emulated/0/Download/images (4).jpg and you ask for mimetype, it returns null.Effete
m3u8 is also returning nullHussite
it returns null .... @Diederik it shows 503 server error . your solution . grepcode.com/file/repo1.maven.org/maven2/com.google.okhttp/…Bayonet
Try this link instead: android.googlesource.com/platform/libcore/+/…Transcendence
I wasn't using a URL but just the file's full name, and the name contained spaces so the MimeTypeMap.getFileExtensionFromUrl(url) returned an empty String "". Therefore the type returned was null. So I used the following method to get the Extension: String extension = url.substring(url.lastIndexOf(".") + 1);Directrix
B
233

Detect mime type of any file

public String getMimeType(Uri uri) {           
    String mimeType = null;
    if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
        ContentResolver cr = getAppContext().getContentResolver();
        mimeType = cr.getType(uri);
    } else {
        String fileExtension = MimeTypeMap.getFileExtensionFromUrl(uri
                .toString());
        mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
                fileExtension.toLowerCase());
    }
    return mimeType;
}
Buttery answered 29/7, 2015 at 5:23 Comment(7)
This should be the correct answer. toLowerCase() did the trick.Aconcagua
This is by far the best answer but it fails miserably if the file name has a special character, in my case an apostrophe! Eg. file name = Don't go baby.mp3. The PatternMatcher inside MimeTypeMap.getFileExtensionFromUrl() can not handle the file name and returns empty String; null comes out to be the mimetype String!Takashi
There is a similar but error free solution below by I. Shvedenenko Worked for the issues I've pointed out above. But this answer was a pointer in correct direction.Takashi
this code returns null with String "/storage/emulated/0/dcim/screenshots/screenshot_20190319-123828_ubl digital app.jpg" .Dead
@Dead It is because that path does not have a Uri scheme. It should either start with file:// or content://.Stonewall
Why is the ContentResolver needed here? I thought file extension should be clear in the Uri, isn't it?Teddytedeschi
not working if actual image is gif but contains jpg extensionStickseed
U
37

The MimeTypeMap solution above returned null in my usage. This works, and is easier:

Uri uri = Uri.fromFile(file);
ContentResolver cR = context.getContentResolver();
String mime = cR.getType(uri);
Unifilar answered 13/1, 2013 at 2:17 Comment(6)
This method also can return null.Merat
It looks like it can return null or not, according the URI. No body seems to know why ;-(Zamboanga
If the media is selected from android gallery then TYPE is returned. If selected from File Manager then null is returned.Aspergillum
I can positively confirm what Rahul said, just tested it and he is rightCockerham
In some devices if i select image from gallery also it is returning nullAspen
@KalpeshPatel said it right, it is mentioned in the documentation as well.Lavenialaver
C
30

Optimized version of Jens' answere with null-safety and fallback-type.

@NonNull
static String getMimeType(@NonNull File file) {
    String type = null;
    final String url = file.toString();
    final String extension = MimeTypeMap.getFileExtensionFromUrl(url);
    if (extension != null) {
        type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.toLowerCase());
    }
    if (type == null) {
        type = "image/*"; // fallback type. You might set it to */*
    }
    return type;
}

Important: getFileExtensionFromUrl() only works with lowercase!


Update (19.03.2018)

Bonus: Above methods as a less verbose Kotlin extension function:

fun File.getMimeType(fallback: String = "image/*"): String {
    return MimeTypeMap.getFileExtensionFromUrl(toString())
            ?.run { MimeTypeMap.getSingleton().getMimeTypeFromExtension(toLowerCase()) }
            ?: fallback // You might set it to */*
}
Coleslaw answered 7/10, 2016 at 18:31 Comment(5)
this worked. bit overly verbose for my liking though.Bilge
Of course this can be writter in a shorter manner. With Kotlin probably only two or three lines, however the foxus was on the null safety and toLoverCase part.Coleslaw
@filthy_wizard, added an optimized version just for you ;-)Coleslaw
As for me using getPath() method instead of toString() is more clear, and just path using kotlin property access syntax.Headship
I appreciate being thorough, but a fallback type defeats the purpose. If you are setting an arbitrary value on failure, why check at all?Tunnell
H
16
File file = new File(path, name);

    MimeTypeMap mime = MimeTypeMap.getSingleton();
    int index = file.getName().lastIndexOf('.')+1;
    String ext = file.getName().substring(index).toLowerCase();
    String type = mime.getMimeTypeFromExtension(ext);

    intent.setDataAndType(Uri.fromFile(file), type);
    try
    {
      context.startActivity(intent);
    }
    catch(ActivityNotFoundException ex)
    {
        ex.printStackTrace();

    }
Heavensent answered 14/1, 2014 at 13:49 Comment(1)
Works perfect for me! But how about using the FilenameUtils.getExetension(path) to get the file extension?Expressly
R
9

In kotlin it's way simpler.

Solution 1:

fun getMimeType(file: File): String? = 
    MimeTypeMap.getSingleton().getMimeTypeFromExtension(file.extension)

Solution 2: (File extension fuction)

fun File.mimeType(): String? = 
    MimeTypeMap.getSingleton().getMimeTypeFromExtension(this.extension)
Raindrop answered 18/10, 2021 at 5:13 Comment(0)
T
7

Pay super close attention to umerk44's solution above. getMimeTypeFromExtension invokes guessMimeTypeTypeFromExtension and is CASE SENSITIVE. I spent an afternoon on this then took a closer look - getMimeTypeFromExtension will return NULL if you pass it "JPG" whereas it will return "image/jpeg" if you pass it "jpg".

Thirtytwomo answered 18/1, 2014 at 23:56 Comment(0)
H
7

EDIT

I created a small library for this. But the underlying code is nearly the same.

It's available on GitHub

MimeMagic-Android

Solution September 2020

Using Kotlin

fun File.getMimeType(context: Context): String? {
    if (this.isDirectory) {
        return null
    }

    fun fallbackMimeType(uri: Uri): String? {
        return if (uri.scheme == ContentResolver.SCHEME_CONTENT) {
            context.contentResolver.getType(uri)
        } else {
            val extension = MimeTypeMap.getFileExtensionFromUrl(uri.toString())
            MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.toLowerCase(Locale.getDefault()))
        }
    }

    fun catchUrlMimeType(): String? {
        val uri = Uri.fromFile(this)

        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val path = Paths.get(uri.toString())
            try {
                Files.probeContentType(path) ?: fallbackMimeType(uri)
            } catch (ignored: IOException) {
                fallbackMimeType(uri)
            }
        } else {
            fallbackMimeType(uri)
        }
    }

    val stream = this.inputStream()
    return try {
        URLConnection.guessContentTypeFromStream(stream) ?: catchUrlMimeType()
    } catch (ignored: IOException) {
        catchUrlMimeType()
    } finally {
        stream.close()
    }
}

That seems like the best option as it combines the previous answers.

First it tries to get the type using URLConnection.guessContentTypeFromStream but if this fails or returns null it tries to get the mimetype on Android O and above using

java.nio.file.Files
java.nio.file.Paths

Otherwise if the Android Version is below O or the method fails it returns the type using ContentResolver and MimeTypeMap

Heronry answered 16/9, 2020 at 17:20 Comment(1)
Close the InputStreamAdame
D
6

Here is the solution which I used in my Android app:

public static String getMimeType(String url)
    {
        String extension = url.substring(url.lastIndexOf("."));
        String mimeTypeMap = MimeTypeMap.getFileExtensionFromUrl(extension);
        String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(mimeTypeMap);
        return mimeType;
    }
Driftwood answered 1/9, 2013 at 9:38 Comment(1)
url? A lot of url doesn't have extension. For example this page doesn't have extension. For url you should use new URL(url).openConnection().getRequestProperty("Content-type");Danilodanio
E
6

I tried to use standard methods to determine the mime type, but I cannot retain the file extension using MimeTypeMap.getFileExtensionFromUrl(uri.getPath()). This method returned me an empty string. So I made a non-trivial solution to retain the file extension.

Here is the method returning the file extension:

private String getExtension(String fileName){
    char[] arrayOfFilename = fileName.toCharArray();
    for(int i = arrayOfFilename.length-1; i > 0; i--){
        if(arrayOfFilename[i] == '.'){
            return fileName.substring(i+1, fileName.length());
        }
    }
    return "";
}

And having retained the file extension, it is possible to get mime type like below:

public String getMimeType(File file) {
    String mimeType = "";
    String extension = getExtension(file.getName());
    if (MimeTypeMap.getSingleton().hasExtension(extension)) {
        mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
    }
    return mimeType;
}
Elseelset answered 3/6, 2016 at 21:35 Comment(6)
Man, this nailed all the answers posted here on this problem! I had the same issue with all the Legacy classes. Issue was same as you've mentioned, MimeTypeMap.getFileExtensionFromUrl returned empty string for the Filenames which have invalid characters as per internal implementation of a PatternMatcher. This worked for me completely! Loved it, no issues so far!Takashi
@I. Shvedenenko String extension = file.getName().split("\\.")[1] would also have worked, thereby, eliminating the getExtension() method.Viand
But the thing is, what if a wrong extension is used while creating the file? Should extension be the sole judge of mime type?Viand
Looks like you have problems with this solution if there's more than one . in the filename. In Kotlin, val extension: String = file.name.split(".").last() eliminates the need for getExtension and the more than one . problem.Marsland
If you are still working on Java: file.getName().substring(file.getName().lastIndexOf("."))Mosquito
fileName.length() is redundant. substring definition: Returns a string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.Janitress
G
5

Sometimes Jeb's and Jens's answers don't work and return null. In this case I use follow solution. Head of file usually contains type signature. I read it and compare with known in list of signatures.

/**
 *
 * @param is InputStream on start of file. Otherwise signature can not be defined.
 * @return int id of signature or -1, if unknown signature was found. See SIGNATURE_ID_(type) constants to
 *      identify signature by its id.
 * @throws IOException in cases of read errors.
 */
public static int getSignatureIdFromHeader(InputStream is) throws IOException {
    // read signature from head of source and compare with known signatures
    int signatureId = -1;
    int sigCount = SIGNATURES.length;
    int[] byteArray = new int[MAX_SIGNATURE_LENGTH];
    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < MAX_SIGNATURE_LENGTH; i++) {
        byteArray[i] = is.read();
        builder.append(Integer.toHexString(byteArray[i]));
    }
    if (DEBUG) {
        Log.d(TAG, "head bytes=" + builder.toString());
    }
    for (int i = 0; i < MAX_SIGNATURE_LENGTH; i++) {

        // check each bytes with known signatures
        int bytes = byteArray[i];
        int lastSigId = -1;
        int coincidences = 0;

        for (int j = 0; j < sigCount; j++) {
            int[] sig = SIGNATURES[j];

            if (DEBUG) {
                Log.d(TAG, "compare" + i + ": " + Integer.toHexString(bytes) + " with " + sig[i]);
            }
            if (bytes == sig[i]) {
                lastSigId = j;
                coincidences++;
            }
        }

        // signature is unknown
        if (coincidences == 0) {
            break;
        }
        // if first bytes of signature is known we check signature for full coincidence
        if (coincidences == 1) {
            int[] sig = SIGNATURES[lastSigId];
            int sigLength = sig.length;
            boolean isSigKnown = true;
            for (; i < MAX_SIGNATURE_LENGTH && i < sigLength; i++) {
                bytes = byteArray[i];
                if (bytes != sig[i]) {
                    isSigKnown = false;
                    break;
                }
            }
            if (isSigKnown) {
                signatureId = lastSigId;
            }
            break;
        }
    }
    return signatureId;
}

signatureId is an index of signature in array of signatures. For example,

private static final int[] SIGNATURE_PNG = hexStringToIntArray("89504E470D0A1A0A");
private static final int[] SIGNATURE_JPEG = hexStringToIntArray("FFD8FF");
private static final int[] SIGNATURE_GIF = hexStringToIntArray("474946");

public static final int SIGNATURE_ID_JPEG = 0;
public static final int SIGNATURE_ID_PNG = 1;
public static final int SIGNATURE_ID_GIF = 2;
private static final int[][] SIGNATURES = new int[3][];

static {
    SIGNATURES[SIGNATURE_ID_JPEG] = SIGNATURE_JPEG;
    SIGNATURES[SIGNATURE_ID_PNG] = SIGNATURE_PNG;
    SIGNATURES[SIGNATURE_ID_GIF] = SIGNATURE_GIF;
}

Now I have file type even if URI of file haven't. Next I get mime type by file type. If you don't know which mime type to get, you can find proper in this table.

It works for a lot of file types. But for video it doesn't work, because you need to known video codec to get a mime type. To get video's mime type I use MediaMetadataRetriever.

Gumbotil answered 13/3, 2015 at 13:11 Comment(0)
G
4

its works for me and flexible both for content and file

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;
}
Greatly answered 18/9, 2020 at 16:44 Comment(0)
T
3

For Xamarin Android (From @HoaLe's answer above)

public String getMimeType(Uri uri) {
    String mimeType = null;
    if (uri.Scheme.Equals(ContentResolver.SchemeContent))
    {
        ContentResolver cr = Application.Context.ContentResolver;
        mimeType = cr.GetType(uri);
    }
    else
    {
        String fileExtension = MimeTypeMap.GetFileExtensionFromUrl(uri.ToString());
        mimeType = MimeTypeMap.Singleton.GetMimeTypeFromExtension(
        fileExtension.ToLower());
    }
    return mimeType;
}
Teteak answered 21/6, 2017 at 9:50 Comment(0)
B
2

MimeTypeMap may not recognize some file extensions like flv,mpeg,3gpp,cpp. So you need to think how to expand the MimeTypeMap for maintaining your code. Here is such an example.

http://grepcode.com/file/repo1.maven.org/maven2/com.google.okhttp/okhttp/20120626/libcore/net/MimeUtils.java#MimeUtils

Plus, here is a complete list of mime types

http: //www.sitepoint.com/web-foundations/mime-types-complete-list/

Brusque answered 18/9, 2014 at 20:32 Comment(0)
W
1
get file object....
File file = new File(filePath);

then....pass as a parameter to...

getMimeType(file);

...here is 


public String getMimeType(File file) {
        String mimetype = MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(file).toString()).toLowerCase());
        if (mimetype == null) {
            return "*/*";
        }
        return mimetype;///return the mimeType
    }
Willard answered 25/2, 2016 at 11:42 Comment(0)
Y
1

While from asset/file(Note that few cases missing from the MimeTypeMap).

private String getMimeType(String path) {
    if (null == path) return "*/*";

    String extension = path;
    int lastDot = extension.lastIndexOf('.');
    if (lastDot != -1) {
        extension = extension.substring(lastDot + 1);
    }

    // Convert the URI string to lower case to ensure compatibility with MimeTypeMap (see CB-2185).
    extension = extension.toLowerCase(Locale.getDefault());
    if (extension.equals("3ga")) {
        return "audio/3gpp";
    } else if (extension.equals("js")) {
        return "text/javascript";
    } else if (extension.equals("woff")) {
        return "application/x-font-woff";
    } else {
        // TODO
        // anyting missing from the map (http://www.sitepoint.com/web-foundations/mime-types-complete-list/)
        // reference: http://grepcode.com/file/repo1.maven.org/maven2/com.google.okhttp/okhttp/20120626/libcore/net/MimeUtils.java#MimeUtils
    }

    return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}

While use ContentResolver

contentResolver.getType(uri)

While http/https request

    try {
        HttpURLConnection conn = httpClient.open(new URL(uri.toString()));
        conn.setDoInput(false);
        conn.setRequestMethod("HEAD");
        return conn.getHeaderField("Content-Type");
    } catch (IOException e) {
    }
Yokoyama answered 29/3, 2016 at 8:1 Comment(0)
T
1
// This will return the mimeType. 
// for eg. xyz.png it will return image/png. 
// here uri is the file that we were picked using intent from ext/internal storage.
private String getMimeType(Uri uri) {
   // This class provides applications access to the content model.  
   ContentResolver contentResolver = getContentResolver();

   // getType(Uri url)-Return the MIME type of the given content URL. 
   return contentResolver.getType(uri);
}
Transcribe answered 13/4, 2019 at 15:49 Comment(2)
Please provide some explanation. It will help initial reader to adapt her/his code and further readers to get the most value from your answer.Mach
thanks for your response. I edit it with explanation.Transcribe
M
1

I faced similar problem. So far I know result may different for different names, so finally came to this solution.

public String getMimeType(String filePath) {
    String type = null;
    String extension = null;
    int i = filePath.lastIndexOf('.');
    if (i > 0)
        extension = filePath.substring(i+1);
    if (extension != null)
        type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
    return type;
}  
Macgregor answered 17/4, 2019 at 20:11 Comment(0)
T
1

I don't realize why MimeTypeMap.getFileExtensionFromUrl() has problems with spaces and some other characters, that returns "", but I just wrote this method to change the file name to an admit-able one. It's just playing with Strings. However, It kind of works. Through the method, the spaces existing in the file name is turned into a desirable character (which, here, is "x") via replaceAll(" ", "x") and other unsuitable characters are turned into a suitable one via URLEncoder. so the usage (according to the codes presented in the question and the selected answer) should be something like getMimeType(reviseUrl(url)).

private String reviseUrl(String url) {

        String revisedUrl = "";
        int fileNameBeginning = url.lastIndexOf("/");
        int fileNameEnding = url.lastIndexOf(".");

        String cutFileNameFromUrl = url.substring(fileNameBeginning + 1, fileNameEnding).replaceAll(" ", "x");

        revisedUrl = url.
                substring(0, fileNameBeginning + 1) +
                java.net.URLEncoder.encode(cutFileNameFromUrl) +
                url.substring(fileNameEnding, url.length());

        return revisedUrl;
    }
Thirteenth answered 8/12, 2019 at 17:0 Comment(0)
D
0

The above solution returned null in case of .rar file, using URLConnection.guessContentTypeFromName(url) worked in this case.

Dropkick answered 29/8, 2013 at 8:51 Comment(0)
T
0

mime from local file:

String url = file.getAbsolutePath();
FileNameMap fileNameMap = URLConnection.getFileNameMap();
String mime = fileNameMap.getContentTypeFor("file://"+url);
Tegantegmen answered 10/6, 2015 at 19:15 Comment(0)
C
0

you have multiple choice to get extension of file:like: 1-String filename = uri.getLastPathSegment(); see this link

2-you can use this code also

 filePath .substring(filePath.lastIndexOf(".")+1);

but this not good aproch. 3-if you have URI of file then use this Code

String[] projection = { MediaStore.MediaColumns.DATA,
MediaStore.MediaColumns.MIME_TYPE };

4-if you have URL then use this code:

 public static String getMimeType(String url) {
String type = null;
String extension = MimeTypeMap.getFileExtensionFromUrl(url);
if (extension != null) { 


  type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
    }

return type;
}

enjoy your code:)

Caterinacatering answered 25/8, 2015 at 5:15 Comment(0)
R
0
// new processing the mime type out of Uri which may return null in some cases
String mimeType = getContentResolver().getType(uri);
// old processing the mime type out of path using the extension part if new way returned null
if (mimeType == null){mimeType URLConnection.guessContentTypeFromName(path);}
Regionalism answered 7/11, 2015 at 8:58 Comment(0)
H
0
public static String getFileType(Uri file)
{
    try
    {
        if (file.getScheme().equals(ContentResolver.SCHEME_CONTENT))
            return subStringFromLastMark(SystemMaster.getContentResolver().getType(file), "/");
        else
            return MimeTypeMap.getFileExtensionFromUrl(file.toString()).toLowerCase();
    }
    catch(Exception e)
    {
        return null;
    }
}

public static String getMimeType(Uri file)
{
    try
    {
        return MimeTypeMap.getSingleton().getMimeTypeFromExtension(getFileType(file));
    }
    catch(Exception e)
    {
        return null;
    }
}

public static String subStringFromLastMark(String str,String mark)
{
    int l = str.lastIndexOf(mark);
    int end = str.length();
    if(l == -1)
        return str;

    return str.substring(l + 1, end);
}
Humberto answered 15/10, 2017 at 5:41 Comment(0)
R
0

Has also return null value in my case path was

/storage/emulated/0/Music/01 - Ghost on the Dance Floor.mp3

as work around use

val url = inUrl.replace(" ","")

so method looks like

@JvmStatic
    fun getMimeType(inUrl: String?): String {
        if (inUrl == null) return ""

        val url = inUrl.replace(" ","")
        var type: String? = null

        val extension = MimeTypeMap.getFileExtensionFromUrl(url)
        if (extension != null) {
            type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.toLowerCase())
        }

        if(type ==null){
            val cR = WifiTalkie.getApplicationContext().contentResolver
            type = cR.getType(Uri.parse(url))
        }

        if (type == null) {
            type = "*/*" // fallback method_type. You might set it to */*
        }
        return type
    }

as result it return success result:

audio/mpeg

Hope it helps anybody

Relationship answered 23/4, 2018 at 13:57 Comment(0)
M
0

None of the answers here are perfect. Here is an answer combining the best elements of all the top answers:

public final class FileUtil {

    // By default, Android doesn't provide support for JSON
    public static final String MIME_TYPE_JSON = "application/json";

    @Nullable
    public static String getMimeType(@NonNull Context context, @NonNull Uri uri) {

        String mimeType = null;
        if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
            ContentResolver cr = context.getContentResolver();
            mimeType = cr.getType(uri);
        } else {
            String fileExtension = getExtension(uri.toString());

            if(fileExtension == null){
                return null;
            }

            mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
                    fileExtension.toLowerCase());

            if(mimeType == null){
                // Handle the misc file extensions
                return handleMiscFileExtensions(fileExtension);
            }
        }
        return mimeType;
    }

    @Nullable
    private static String getExtension(@Nullable String fileName){

        if(fileName == null || TextUtils.isEmpty(fileName)){
            return null;
        }

        char[] arrayOfFilename = fileName.toCharArray();
        for(int i = arrayOfFilename.length-1; i > 0; i--){
            if(arrayOfFilename[i] == '.'){
                return fileName.substring(i+1, fileName.length());
            }
        }
        return null;
    }

    @Nullable
    private static String handleMiscFileExtensions(@NonNull String extension){

        if(extension.equals("json")){
            return MIME_TYPE_JSON;
        }
        else{
            return null;
        }
    }
}
Melbamelborn answered 22/8, 2018 at 6:27 Comment(0)
G
0
Intent myIntent = new Intent(android.content.Intent.ACTION_VIEW);
                        File file = new File(filePatch); 
                        Uri uris = Uri.fromFile(file);
                        String mimetype = null;
                        if 
(uris.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
                            ContentResolver cr = 
getApplicationContext().getContentResolver();
                            mimetype = cr.getType(uris);
                        } else {
                            String fileExtension = 
MimeTypeMap.getFileExtensionFromUrl(uris.toString());
mimetype =  MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension.toLowerCase());
                        }
Gasometer answered 8/9, 2018 at 9:3 Comment(0)
B
0

I consider the easiest way is to refer to this Resource file: https://android.googlesource.com/platform/libcore/+/master/luni/src/main/java/libcore/net/android.mime.types

Bloodletting answered 12/9, 2019 at 11:49 Comment(1)
The link is brokenFreckle
I
0

Adding my 50 cents Try using mime-types library. Code and requirements seems much simpler for detection based on path than apache tika and other tools

File file = new File("foo.txt");
MimeTypeDetector detector = new MimeTypeDetector();
String mimeType = detector.detectMimeType(file); // "text/plain"
Irrepressible answered 29/1 at 22:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.