How to check file mime type with JavaScript before upload?

Estimated read time 2 min read

You can check the file MIME type before uploading a file in JavaScript using the File and FileReader objects. Here’s an example:

document.getElementById("file").addEventListener("change", function() {
  let file = this.files[0];
  let reader = new FileReader();

  reader.onload = function(e) {
    let mimeType = e.target.result.split(",")[0].split(":")[1].split(";")[0];
    console.log(mimeType);
  };

  reader.readAsDataURL(file);
});

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 create a FileReader object.

The FileReader object reads the contents of the file as a data URL, which contains the MIME type of the file in the format data:<MIME type>;base64,<file data>. We use string manipulation to extract the MIME type from the data URL and log it to the console.

Note that this approach only works for checking the MIME type of the file. It does not guarantee that the file is of the correct format or that it can be successfully uploaded to the server. Additional validation may be necessary to ensure the file meets your requirements.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply