js验证图片真实格式(针对手动修改后缀名)
js验证图片真实格式(针对手动修改后缀名)
- <input type="file" id="file" onchange="handleFiles(this.files)"/>
- <script>
- function handleFiles(files) {
- if (files.length) {
- var file = files[0];
- console.log(file.name);
- console.log(getFileExt(file));
- }
- }
- function getFileExt(file)
- {
- var index = file.name.lastIndexOf('.');
- var fileExt = file.name.substring(index+1);
- return fileExt;
- }
- function checkFileType(file){
- var reader = new FileReader();
- reader.onload = function() {
- return getImageExt(this.result);
- }
- reader.readAsBinaryString(file);
- }
- function getImageExt(bin){
- var ext='';
- var hexCode='';
- for (var i=0;i<4;i++){
- var charCode = bin[i];
- console.log(charCode);
- var code = charCode.charCodeAt();
- console.log(code);
- hexCode = hexCode+ code.toString(16);
- }
- hexCode = hexCode.toUpperCase();
- console.log(hexCode);
- if(hexCode.substring(0,4)=="424D"){
- return "bmp";
- }
- if (hexCode.substring(0,6)=="FFD8FF") {
- return "jpg";
- }
- if (hexCode == "89504E47") {
- return "png";
- }
- if(hexCode == "47494638") {
- return "gif";
- }
- if(hexCode == "49492A00") {
- return "tif";
- }
- return "undefined";
- }
- </script>
附:常见文件文件头