Last updated: Mar 7, 2024
Reading timeยท8 min
Note: if you need to get the MIME type of a file in
Node.js
, click on the following subheading:
To get the MIME type of a file in the browser:
files
property on the input
element with a type of file
.type
property on each file to get its MIME type.Here is the HTML for the example.
<!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>
And here is the related JavaScript file.
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); } });
You can also access the files
property directly on the fileInput
element
(without using the event
object).
// 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.
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.
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 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.
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.
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); }
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.
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.
default: { mimeType = file.type; break; }
You could adjust this to handle an unknown MIME type according to your use case.
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.
<!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>
And here is the related JavaScript code.
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 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.
// ๐๏ธ 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'
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.
To get the MIME type of a file in Node.js:
mime
NPM package by running the npm install mime
command.# 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
getType()
method.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.
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.
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.
# 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.
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.
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.
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.
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.
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.
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.
file-type
module to get the MIME type of a file in Node.jsYou 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.
# 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.
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 filemime
- the MIME type of the fileThe method returns a Promise, so make sure to await
it or use the .then()
syntax.
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.
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.
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.
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.
# 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.
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.
You can learn more about the related topics by checking out the following tutorials: