代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>判断图片类型</title>
<script type="text/javascript" src="jquery-1.11.3.min.js"></script>
</head>
<body>
<input type="file" multiple="true" id="upload" />
</body>
<script type="text/javascript">
function checkRealMimeType(file, callback) {
let realMimeType
let reader = new FileReader()
//running asynchronously!
reader.onloadend = function () {
let arr = new Uint8Array(reader.result).subarray(0, 4)
let header = ''
for (let i = 0; i < arr.length; i++) {
header += arr[i].toString(16)
}
console.log(header)
//在这里可以得到上传图片的真实mintype类型
//在这里执行你的逻辑,该方法是异步执行
if (header.indexOf('8950') === 0) {
realMimeType = 'png'
} else if (header.indexOf('424d') === 0) {
realMimeType = 'bmp'
} else if (header.indexOf('ffd8') === 0) {
realMimeType = 'jpeg'
} else {
realMimeType = null
}
console.log(realMimeType)
}
reader.readAsArrayBuffer(file)
}
$('#upload').on('change', function (e) {
checkRealMimeType($('#upload')[0].files[0])
})
</script>
</html>