How to check file type when the file is selected with JavaScript?

Estimated read time 1 min read

You can check the file type of an uploaded file in JavaScript using the File object, which is part of the HTML5 File API. Here’s an example:

document.getElementById("file").addEventListener("change", function() {
  let file = this.files[0];
  let type = file.type;
  console.log(type);
});

In this example, we use an event listener to listen for a change in the file input field. When a file is selected, we get the first file from the files array and access its type property, which returns the MIME type of the file.

Finally, we log the MIME type to the console.

Note that the value of the type property is determined by the browser based on the file’s extension, and may not accurately reflect the actual content of the file. Additional validation may be necessary to ensure that the file meets your requirements.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply