How to check file MIME type with JavaScript before upload?

Spread the love

Sometimes, we want to check file MIME type with JavaScript before upload.

In this article, we’ll look at how to check file MIME type with JavaScript before upload.

How to check file MIME type with JavaScript before upload?

To check file MIME type with JavaScript before upload, we get the type property of the file object.

For instance, we write

const [fileVariable] = document.getElementsById("fileId").files;
if (fileVariable.type.match("image.*")) {
  alert("its an image");
}

to get the file input with getElementsById.

We get the selected files from the files property.

And then we get the MIME type of the file with fileVariable.type, which is a string.

Conclusion

To check file MIME type with JavaScript before upload, we get the type property of the file object.

Leave a Reply

Your email address will not be published.