Home > Back-end >  How to get generic (top level) mime type of URI
How to get generic (top level) mime type of URI

Time:12-26

I have an array of supported file (mime) types

arrayOf(
    "image/*,
    "video/*",
    "audio/*",
    "pdf/*"
)

and I do have a URI for a selected file. When I get the URI type using content resolver it gives me the specific file type like "image/png".

contentResolver.getType(uri) // returns "image/png"

Is there any way to get the high-level mime type i.e. "image/*"? If not, what is the best way to manually check if the file type is in my array?

CodePudding user response:

As mentioned in the comment, you can just use the mime type string that you get & do string manipulation to fit to your needs.

Example:

private fun getTopLevelMimeType(type: String): String {
        return type.substring(0, type.indexOf("/")   1)   "*"
    }

Usage:

val topLevelMimeType = getTopLevelMimeType("image/png")
        Log.d("topLevelMimeType", topLevelMimeType)//logs "image/*"

CodePudding user response:

Apparently, there is no way Android SDK does it for us, so we have to do it manually.

private fun isTypeSupported(contentResolver: ContentResolver?, uri: Uri): Boolean = contentResolver?.let { cr ->
    val type = cr.getType(uri)
    getSupportedFileTypes().any { type?.contains(it.dropLast(1)) ?: false }
} ?: false

CodePudding user response:

val supportedFileTypes = arrayOf(
  "image/*",
  "video/*",
  "audio/*",
  "pdf/*"
)

fun isTypeSupported(type: String): Boolean {
  return supportedFileTypes.contains(type.substringBefore("/")   "/*" )
}

println(isTypeSupported("image/png"))
  • Related