Despite server-side validation being essential, carrying out client-side checks can prevent unnecessary server resource consumption. While the MIME type is often determined based on file extension, that approach can be unreliable. Here's a two-step process you can follow to verify MIME types using JavaScript before uploading:
Obtain file details from an element as shown below:
var control = document.getElementById("your-files"); control.addEventListener("change", function(event) { var files = control.files, for (var i = 0; i < files.length; i++) { console.log("Filename: " + files[i].name); console.log("Type: " + files[i].type); console.log("Size: " + files[i].size + " bytes"); } }, false);
Utilize the FileReader API to examine the file's header.
Quick Method: Directly retrieve the MIME type from the file blob:
console.log(blob.type);
Reliable Method: Analyze the raw file header bytes:
var fileReader = new FileReader(); fileReader.onloadend = function(e) { // code to obtain file header goes here }; fileReader.readAsArrayBuffer(blob);
Compare the header against known signatures to determine the actual MIME type. For instance, JPEG signatures could be:
case "ffd8ffe0": case "ffd8ffe1": case "ffd8ffe2": type = "image/jpeg"; break;
Finally, accept or reject file uploads based on the expected MIME types.
Note: It's critical to realize that even if a file is renamed, its true MIME type can be established using this technique.
The above is the detailed content of How Can I Verify File MIME Types in JavaScript Before Uploading?. For more information, please follow other related articles on the PHP Chinese website!