How to get the MIME type of a File in JavaScript & Node.js

avatar
Borislav Hadzhiev

Last updated: Mar 7, 2024
8 min

banner

# Table of Contents

  1. Get the MIME type of a File in the Browser
  2. Getting the MIME type of a file in the Browser by reading the file
  3. Get the MIME type of a file from an extension in the Browser
  4. Getting the MIME type of a file in Node.js
  5. Using the mime-types module to get the MIME type of a file in Node.js
  6. Using the file-type module to get the MIME type of a file in Node.js

Note: if you need to get the MIME type of a file in Node.js, click on the following subheading:

# Get the MIME type of a File in the Browser

To get the MIME type of a file in the browser:

  1. Access the files property on the input element with a type of file.
  2. Access the type property on each file to get its MIME type.

Here is the HTML for the example.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <style> body { margin: 100px; } </style> </head> <body> <div> <input type="file" id="file-input" multiple /> </div> <script src="index.js"></script> </body> </html>
The code for this article is available on GitHub

And here is the related JavaScript file.

index.js
const fileInput = document.getElementById('file-input'); fileInput.addEventListener('change', event => { const files = event.target.files; for (const file of files) { console.log(`filename: ${file.name}`); console.log(`file size: ${file.size} bytes`); console.log(`file type: ${file.type}`); const mimeType = file.type; console.log(mimeType); } });

get mime type of file

The code for this article is available on GitHub

You can also access the files property directly on the fileInput element (without using the event object).

index.js
// Accessing files property directly on `fileInput` fileInput.addEventListener('change', () => { const files = fileInput.files; })

Either approach works because the event.target property refers to the fileInput field.

Here is a short clip that demonstrates how this works.

get mime type of file browser

You can also select multiple files by pressing and holding Ctrl (or Cmd on macOS) and left-clicking multiple files.

We used a for...of loop, so the extension of each file will get logged to the console.

In order to get the MIME type of each file, we simply access the file's type property.

index.js
for (const file of files) { console.log(`filename: ${file.name}`); console.log(`file size: ${file.size} bytes`); console.log(`file type: ${file.type}`); const mimeType = file.type; console.log(mimeType); }
The code for this article is available on GitHub

The File.type property returns the media type (MIME) of the file that is represented by the File object.

For example, the property returns the string image/png for PNG images and the string text/plain for .txt files.

# Getting the MIME type of a file in the Browser by reading the file

However, note that browsers don't read the bytestream of the file to determine its media type.

Instead, they read the file's extension.

This means that the user could change the MIME type of the file by changing its extension.

For example, if you rename a PNG image to have a .txt extension and you upload it, then the file.type property would return text/plain and not image/png.

Here is an example of how you could read the first few bytes of a file and check its signature to be sure that the file is of the given MIME type.

index.js
const fileInput = document.getElementById('file-input'); fileInput.addEventListener('change', event => { const files = event.target.files; for (const file of files) { getMimeType(file, mimeType => { console.log('The MIME Type is: ', mimeType); }); } }); function getMimeType(file, callback) { const fileReader = new FileReader(); fileReader.onloadend = function (event) { let mimeType = ''; const arr = new Uint8Array(event.target.result).subarray( 0, 4, ); let header = ''; for (let index = 0; index < arr.length; index++) { header += arr[index].toString(16); } console.log('Header:', header); // View other byte signature patterns here: // 1) https://mimesniff.spec.whatwg.org/#matching-an-image-type-pattern // 2) https://en.wikipedia.org/wiki/List_of_file_signatures switch (header) { case '89504e47': { mimeType = 'image/png'; break; } case '47494638': { mimeType = 'image/gif'; break; } case '52494646': case '57454250': mimeType = 'image/webp'; break; case '49492A00': case '4D4D002A': mimeType = 'image/tiff'; break; case 'ffd8ffe0': case 'ffd8ffe1': case 'ffd8ffe2': case 'ffd8ffe3': case 'ffd8ffe8': mimeType = 'image/jpeg'; break; default: { mimeType = file.type; break; } } callback(mimeType); }; fileReader.readAsArrayBuffer(file); }

get mime type by reading file

The code for this article is available on GitHub

The code sample only checks for a couple of image MIME types but you could add more case statements.

You can view the byte patterns of files with other extensions in this table.

Or you could simply upload a file and check what the header variable prints to determine the case string.

The code sample reads the first 4 bytes of the uploaded file and compares then to the expected byte pattern.

If there is a match, the mimeType variable is set to the matching MIME type.

If there isn't a match, the default case uses the browser's file.type property.

index.js
default: { mimeType = file.type; break; }

You could adjust this to handle an unknown MIME type according to your use case.

# Get the MIME type of a file from an extension in the Browser

You can use the mime NPM package if you need to get the mime type of a file from its extension or file name.

Here is the HTML for the example.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div> <input type="file" id="file-input" multiple /> </div> <script type="module" src="index.js"></script> </body> </html>
The code for this article is available on GitHub

And here is the related JavaScript code.

index.js
import mime from 'https://cdn.skypack.dev/mime'; // โœ… Get mime type of file from filename or extension console.log(mime.getType('txt')); // 'text/plain' console.log(mime.getType('webp')); // 'image/webp' console.log(mime.getType('cat.png')); // 'image/png' console.log(mime.getType('nature.jpeg')); // 'image/jpeg' // โœ… Get the extension from the MIME type console.log(mime.getExtension('text/plain')); //'txt' console.log(mime.getExtension('image/png')); // 'png'
The code for this article is available on GitHub

The mime.getType() method takes the name of the file or its extension and returns the corresponding MIME type.

The mime.getExtension() method takes the MIME type of the file as a parameter and returns the corresponding extension.

There is also a lite version of the module that omits vendor-specific and experimental extensions.

index.js
// ๐Ÿ‘‡๏ธ using `lite` version of `mime` module import mime from 'https://cdn.skypack.dev/mime/lite'; // โœ… Get mime type of file from filename or extension console.log(mime.getType('txt')); // 'text/plain' console.log(mime.getType('webp')); // 'image/webp' console.log(mime.getType('cat.png')); // 'image/png' console.log(mime.getType('nature.jpeg')); // 'image/jpeg' // โœ… Get the extension from the MIME type console.log(mime.getExtension('text/plain')); //'txt' console.log(mime.getExtension('image/png')); // 'png'
The code for this article is available on GitHub

You can view more examples of using the mime module in the package's NPM page.

If you need to manually check the MIME type for a specific extension, check out this MDN table.

# Getting the MIME type of a file in Node.js

To get the MIME type of a file in Node.js:

  1. Install the mime NPM package by running the npm install mime command.
shell
# with NPM npm install mime # or with YARN yarn add mime # ------------------------------ # Only if you use TypeScript npm install @types/mime --save-dev # or yarn yarn add @types/mime --dev

install mime package node

  1. Import the module and use the getType() method.
index.js
import mime from 'mime'; // ๐Ÿ‘‡๏ธ use this import if you use CommonJS require() // const mime = require('mime'); // โœ… Get mime type of file from filename or extension console.log(mime.getType('txt')); // 'text/plain' console.log(mime.getType('webp')); // 'image/webp' console.log(mime.getType('cat.png')); // 'image/png' console.log(mime.getType('nature.jpeg')); // 'image/jpeg' // ๐Ÿ‘‡๏ธ image/jpeg console.log(mime.getType('path/to/nature.jpeg')); // โœ… Get the extension from the MIME type console.log(mime.getExtension('text/plain')); //'txt' console.log(mime.getExtension('image/png')); // 'png'

If you use the CommonJS require() syntax, use the following import instead.

index.js
const mime = require('mime');

The getType() method of the mime module takes a path to a file or an extension and returns the mime type of the file.

If the extension is not recognized or detected, then null is returned.

You can use the getExtension() method if you need to get the extension of a file based on a MIME type.

If you need to manually check the MIME type for a specific extension, check out this MDN table.

# Using the mime-types module to get the MIME type of a file in Node.js

You can also use the mime-types module to get the MIME type of a file in Node.js.

The module's API is similar to that of the mime package, however, the mime-types package doesn't return a fallback value when an extension is not recognized.

Install the module by running the following command.

shell
# with NPM npm install mime-types # with YARN yarn add mime-types # ------------------------------ # Only if you use TypeScript npm install @types/mime-types --save-dev # or with YARN yarn add @types/mime-types --dev

Now import and use the module as follows.

index.js
import mime from 'mime-types'; // ๐Ÿ‘‡๏ธ use this import if you use CommonJS require() // const mime = require('mime-types'); // โœ… Get mime type of file from filename or extension console.log(mime.lookup('txt')); // 'text/plain' console.log(mime.lookup('webp')); // 'image/webp' console.log(mime.lookup('cat.png')); // 'image/png' console.log(mime.lookup('nature.jpeg')); // 'image/jpeg' // ๐Ÿ‘‡๏ธ image/jpeg console.log(mime.lookup('path/to/nature.jpeg'));

The import statement above uses the ES6 import/export syntax.

If you use CommonJS require(), use the following import statement instead.

index.js
const mime = require('mime-types');

The mime.lookup() method takes a file path or an extension and returns the corresponding MIME type.

The method returns false if called with an unknown extension.

index.js
import mime from 'mime-types'; console.log(mime.lookup('unknown')); // false

If you need to get the extension of a file based on a MIME type, use the extension() method.

index.js
import mime from 'mime-types'; // ๐Ÿ‘‡๏ธ use this import if you use CommonJS require() // const mime = require('mime-types'); // โœ… Get the extension from the MIME type console.log(mime.extension('text/plain')); //'txt' console.log(mime.extension('image/png')); // 'png'

If you need to create a full content-type header given a Content-Type or an extension, use the mime.contentType() method.

index.js
import mime from 'mime-types'; // ๐Ÿ‘‡๏ธ use this import if you use CommonJS require() // const mime = require('mime-types'); // ๐Ÿ‘‡๏ธ text/html; charset=utf-8 console.log(mime.contentType('text/html')); // ๐Ÿ‘‡๏ธ image/png console.log(mime.contentType('png')); // ๐Ÿ‘‡๏ธ image/webp console.log(mime.contentType('webp')); // ๐Ÿ‘‡๏ธ application/json; charset=utf-8 console.log(mime.contentType('file.json'));

If the Content-Type doesn't have a charset parameter, the mime.charset method is used to get the default charset.

index.js
import mime from 'mime-types'; // ๐Ÿ‘‡๏ธ use this import if you use CommonJS require() // const mime = require('mime-types'); console.log(mime.charset('text/html')); // UTF-8 console.log(mime.charset('text/markdown')); // UTF-8 console.log(mime.charset('image/webp')); // false

You can view more examples of using the mime-type module in the module's NPM page.

# Using the file-type module to get the MIME type of a file in Node.js

You can also use the popular file-type module to get the MIME type of a file.

The module detects the file type by reading the first few bytes of the file rather than relying on the file's extension which could be changed by the user prior to uploading.

The package is used for detecting binary-based files, not text-based files like .txt, .csv, .svg, etc.

Note that the module is an ESM package and can only be used if your project is configured to use ES6 modules.

Run the following command to install the module.

shell
# with NPM npm install file-type # or with YARN yarn add file-type

Here is an example of using the module with a local file.

index.js
import {fileTypeFromFile} from 'file-type'; // { ext: 'png', mime: 'image/png' } console.log(await fileTypeFromFile('house.png'));

The code sample assumes that you have a house.png file located in the same directory as your index.js script.

The fileTypeFromFile method reads the first few bytes from the file and determines its extension and MIME type.

Notice that the method returns an object that has 2 properties:

  • ext - the extension of the file
  • mime - the MIME type of the file

The method returns a Promise, so make sure to await it or use the .then() syntax.

index.js
import {fileTypeFromFile} from 'file-type'; // using .then() instead of await fileTypeFromFile('house.png').then(result => { // { ext: 'png', mime: 'image/png' } console.log(result); });

Here is an example that uses an async function.

index.js
import {fileTypeFromFile} from 'file-type'; // console.log(await fileTypeFromFile('house.png')); async function getMimeType(filePath) { const result = await fileTypeFromFile(filePath); // ๐Ÿ‘‡๏ธ { ext: 'png', mime: 'image/png' } console.log(result); // ๐Ÿ‘‡๏ธ png console.log(result.ext); // ๐Ÿ‘‡๏ธ image/png console.log(result.mime); } getMimeType('house.png');

You can also use the module to determine a file type from a stream.

index.js
import fs from 'node:fs'; import {fileTypeFromStream} from 'file-type'; const stream = fs.createReadStream('days.mp3'); // ๐Ÿ‘‡๏ธ { ext: 'mp3', mime: 'audio/mpeg' } console.log(await fileTypeFromStream(stream));

The docs also show how to use the fileTypeFromStream() method to get the MIME type of a file from a URL.

index.js
import got from 'got'; import {fileTypeFromStream} from 'file-type'; const url = 'https://upload.wikimedia.org/wikipedia/en/a/a9/Example.jpg'; const stream = got.stream(url); // ๐Ÿ‘‡๏ธ { ext: 'jpg', mime: 'image/jpeg' } console.log(await fileTypeFromStream(stream));

Make sure you have the got module installed to be able to run the code sample.

shell
# install using NPM npm install got # or install using YARN yarn add got

If you use TypeScript, you can also install the typings for the got module.

shell
npm install @types/got --save-dev yarn add @types/got --dev

You can check out more examples of using the file-type package in the package's NPM page.

If you need to manually check the MIME type for a specific extension, check out this MDN table.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev