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

Sometimes, we want to check file type when file is selected with JavaScript.

In this article, we’ll look at how to check file type when file is selected with JavaScript.

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

To check file type when file is selected with JavaScript, we can check the type property of the selected file.

For instance, we write:

<input type="file">

to add a file input.

Then we write:

const input = document.querySelector('input')
const getFileType = (file) => {
  if (file.type.match('image.*'))
    return 'image';
  if (file.type.match('video.*'))
    return 'video';
  if (file.type.match('audio.*'))
    return 'audio';
  return 'other';
}

input.onchange = (e) => {
  const [file] = e.target.files
  console.log(getFileType(file))
}

We select an input with document.querySelector.

Then we define the getfileType function to check the file.type property to check the file type.

Then we set the input.onchange property to a function that get the selected file from e.target.files and call getFileType with it.

Conclusion

To check file type when file is selected with JavaScript, we can check the type property of the selected file.