Android Scope Storage: Get Filename and Mime Type From Uri

January 30, 2020

Assuming you have the media/file uri based on MediaStore.MediaColumns._ID.

On KITKAT / API 19 and above.

val file = DocumentFile.fromSingleUri(context, uri)
if (file != null) {
    Timber.d("uri=$uri, filename=${file.name}, mimeType=${file.type}")
}

No KitKat Restrictions

class MediaFile private constructor(context: Context, uri: Uri) {
    lateinit var displayName: String
    lateinit var mimeType: String

    companion object {
        fun fromUri(context: Context, uri: Uri): MediaFile? {
            return try {
                MediaFile(context, uri)
            }
            catch (e: FileNotFoundException) {
                null
            }
        }
    }

    init {
        val contentResolver = context.contentResolver
        val projection = arrayOf(
            MediaStore.MediaColumns.DISPLAY_NAME,
            MediaStore.MediaColumns.MIME_TYPE
        )
        contentResolver.query(uri, projection, null, null, null).use { cursor ->
            if (cursor == null) throw FileNotFoundException(uri.toString())

            if (cursor.moveToFirst()) {
                val displayNameIndex = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DISPLAY_NAME)
                val mimeTypeIndex = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.MIME_TYPE)

                displayName = cursor.getString(displayNameIndex)
                mimeType = cursor.getString(mimeTypeIndex)
            }
        }
    }
}
val file = DocumentFile.fromSingleUri(context, uri)
if (file != null) {
    Timber.d("uri=$uri, filename=${file.displayName}, mimeType=${file.mimeType}")
}
else {
    Timber.d("File not found: $uri")
}
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.