Sometimes, we may want to add a file upload feature to our web app.
And we have to check the file type of the file before we upload them sometimes.
In this article, we’ll look at how to check the selected file’s MIME type with JavaScript before upload.
Watch the change Event of a File Input
To check the file MIME type with JavaScript before we upload the file, we can listen to the change
event of a file input.
For instance, we can write the following HTML:
<input type="file" multiple>
And the following JavaScript code to watch the files selected:
const control = document.querySelector("input");
control.addEventListener("change", (event) => {
const {
files
} = control;
for (const file of files) {
console.log("Filename: ", file.name);
console.log("Type: ", file.type);
console.log("Size: ", file.size, " bytes");
}
}, false);
We have a file input with the multiple
attribute set to enable multiple file selection.
Then in the JavaScript code, we get the file input with document.querySelector
.
And then we call addEventListener
with the 'change'
argument to watch for changes in file selection in the file input.
In the event listener, we get the files
from the file input control
.
And then we loop through the files
and get the name
, type
, and size
properties of each entry.
name
has the file name string of the selected file.
type
has the MIME type string of the selected file.
And size
has file size number in bytes.
Conclusion
We can get the MIME types of the files selected by the file input by listening to the change
event.
Then we can get the content of the selected files from the files
property of the element.