How to Get the MIME Type of a File in JavaScript
Getting a file's MIME (Multipurpose Internet Mail Extensions) type is a common requirement for validating uploads, setting correct Content-Type headers in API requests, or handling files based on their type. The correct way to do this depends on your environment: are you working in a web browser or in a Node.js server environment?
This guide will teach you the standard, modern methods for getting a file's MIME type in both of these contexts.
In the Browser: Getting the MIME Type
In the browser, you typically get a File object from an <input type="file"> element or a drag-and-drop operation. This object contains the MIME type information provided by the operating system.
Method 1 (Simple): The file.type Property
The simplest and most direct way to get the MIME type in the browser is to access the type property of the File object.
<input type="file" id="file-input" />
Solution:
const fileInput = document.getElementById('file-input');
fileInput.addEventListener('change', (event) => {
const file = event.target.files[0];
if (!file) return;
console.log('Filename:', file.name);
console.log('MIME Type:', file.type);
});
When a user selects a PNG file, the console will log:
Filename: my-image.png
MIME Type: image/png
Important Limitation: This property is not a guarantee. It is based on the file's extension as reported by the user's operating system. A user could rename malicious.exe to safe.png, and the file.type property would misleadingly report "image/png".
Method 2 (Robust): Reading the File Signature
For security-sensitive applications where you need to be certain of a file's true type, you must read its first few bytes to check its "magic number" or file signature. This is a much more advanced technique.
This example shows how to check for a few common image types by reading the start of the file.
function getTrueMimeType(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => {
const arr = new Uint8Array(reader.result).subarray(0, 4);
let header = '';
for (let i = 0; i < arr.length; i++) {
header += arr[i].toString(16);
}
let mimeType;
switch (header) {
case '89504e47':
mimeType = 'image/png';
break;
case '47494638':
mimeType = 'image/gif';
break;
case 'ffd8ffe0':
case 'ffd8ffe1':
mimeType = 'image/jpeg';
break;
default:
mimeType = file.type || 'unknown'; // Fallback to the browser's reported type
break;
}
resolve(mimeType);
};
reader.onerror = reject;
reader.readAsArrayBuffer(file);
});
}
This is a complex but much more secure way to validate a file's type on the client side.
In Node.js: Getting the MIME Type
In a Node.js environment, you do not have a File object from a file input. You are typically working with file paths. There is no built-in Node.js API to get a MIME type from a file path or extension.
The recommended solution uses a Library!
- The standard and best practice is to use a lightweight, well-tested library. The
mime-typespackage is a popular and excellent choice.
- Install the package:
npm install mime-types - Use it to look up the MIME type:
import mime from 'mime-types'; // or const mime = require('mime-types');
// Get MIME type from an extension
console.log(mime.lookup('txt')); // Output: "text/plain"
// Get MIME type from a filename or path
console.log(mime.lookup('my-file.png')); // Output: "image/png"
console.log(mime.lookup('path/to/archive.zip')); // Output: "application/zip"
// Get an extension from a MIME type
console.log(mime.extension('application/json')); // Output: "json"
This is the most reliable and maintainable way to handle MIME types in a Node.js application.
Conclusion
The correct method for getting a file's MIME type depends entirely on your JavaScript environment.
- In the Browser:
- For a quick and simple check, use the
file.typeproperty. Be aware that this is not secure. - For a secure validation, you must read the file's first few bytes to check its file signature.
- For a quick and simple check, use the
- In Node.js:
- The definitive best practice is to use a dedicated library like
mime-types.
- The definitive best practice is to use a dedicated library like