JavaScript can determine file MIME types before they're uploaded, but validate them on the server side for security.
Step 1: Use FileReader API
To get file information:
var files = document.getElementsByTagName('input')[0].files; console.log(files[0].type);
Step 2: Extract MIME Type
Method 1: Using Blob (Can be fooled by file extension)
console.log(files[0].type);
Method 2: Header Inspection (More reliable)
var fileReader = new FileReader(); fileReader.onloadend = function(e) { var header = (new Uint8Array(e.target.result)).subarray(0, 4).toString(16); switch (header) { case "89504e47": type = "image/png"; break; case "47494638": type = "image/gif"; break; case "ffd8ffe0": case "ffd8ffe1": case "ffd8ffe2": type = "image/jpeg"; break; default: type = "unknown"; break; } }; fileReader.readAsArrayBuffer(files[0]);
Note:
The above is the detailed content of How Can Browsers Reliably Check MIME Types Before File Upload?. For more information, please follow other related articles on the PHP Chinese website!