Find MIME type by file extension
C#, JavaScript and Python examples for detecting a likely MIME type from a file extension, with notes for uploads and content checks.
Every application that accepts uploads has to determine the type of the incoming file. The type reported by the browser cannot be trusted (the user controls it), so the type is usually resolved from the extension. The C# and JavaScript versions are below.
In C# no extra library is needed: the provider shipped with ASP.NET Core carries hundreds of extension-to-MIME mappings. It returns null for an unknown extension, so check the return value. In JavaScript a small package does the same job.
A security note: a MIME type is a claim, not proof. If you need certainty, inspect the first bytes of the file (its signature) or validate it by processing the content.
C#
public string? GetMimeType(string fileExtension)
{
FileExtensionContentTypeProvider provider = new();
return !provider.TryGetContentType(fileExtension, out string? mimeType) ? null : mimeType;
}
Javascript
First, we need to install the required library using the command below.
npm install mime
const mime = require('mime');
function getMimeType(fileExtension)
{
const mimeType = mime.getType(fileExtension);
return mimeType || null;
}
Python
from mimetypes import MimeTypes
def get_mime_type(file_extension):
mime_types = MimeTypes()
mime_type, _ = mime_types.guess_type(f"dummy.{file_extension}")
return mime_type
Short guide
When to use it
MIME type checks are needed in uploads, document archives, image galleries and APIs that move files. The system should understand what kind of file it received before storing or serving it.
What to watch
- Do not trust only the file extension; inspect the content when possible.
- Use an allowlist for accepted file types.
- Do not store uploaded files in a location where they can execute.
Common mistake
Assuming a file is safe because its name ends with .jpg is dangerous. Upload validation should have more than one layer.
Where this example helps
Small helper snippets like this save time in web applications, mobile app backends, admin panels and API projects. The important part is not copying the example blindly, but adapting it to your data format, security needs and performance expectations.