Bajrang Hudda
Bajrang Hudda

Reputation: 3268

How to get actual file type if it is renamed to something different file extension in android?

I want to upload images on the server, unfortunately, my server supports only jpg/jpeg file formats. If I will upload a png file I will get an error. So before uploading to the server, I want to make sure the file type is only jpg/ jpeg. But I am afraid that some users can change a png file type to jpg just by renaming it. For eg- myfile.png can be renamed easily with myfile.jpg. I used below approach to check file type in Android/ Kotlin -

fun getMimeType(context: Context, uri: Uri): String {
        var mimeType = ""
        mimeType = if (uri.scheme.equals(ContentResolver.SCHEME_CONTENT)) {
            val cr = context.contentResolver
            cr.getType(uri) ?: ""
        } else {
            val fileExtension = MimeTypeMap.getFileExtensionFromUrl(uri
                    .toString())
            MimeTypeMap.getSingleton().getMimeTypeFromExtension(
                    fileExtension.toLowerCase(Locale.getDefault())) ?: ""
        }
        return mimeType
    }

But it returns only jpg/jpeg even in case of png file renamed to jpg. I think it's checking by file extension only. So my question is - Is there any way to check the original file type (in our case it is a png file)?

Happy Coding :-)

Upvotes: 0

Views: 472

Answers (1)

emandt
emandt

Reputation: 2706

You have to check file's Header and verify if it respects JPEG formats (this procedure is valid for many type of files) https://wiki.fileformat.com/image/jpeg/

Upvotes: 1

Related Questions