input框触发上传文件事件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>文件上传根据请求头判断文件类型</title>
</head>
<body>
<input type="file" name="myFile" id="file">
<button onclick="clickBtn()">上传文件按钮</button>
<script src="index.js"></script>
</body>
</html>
index.js
const allowedType = {
'FFD8FFE0': 'jpg',
'89504E47': 'png',
'47494638': 'gif',
"52494646": 'webp'
}
function fileType(file) {
const fileReader = new FileReader()
fileReader.readAsArrayBuffer(file)
return new Promise((resolve, reject) => {
fileReader.onload = (e) => {
try {
let uint8Array = new Uint8Array(e.target.result).slice(0, 4)
let key = Array.prototype.map.call(uint8Array, s => s.toString(16).toUpperCase().padStart(2, '0')).join('')
console.log(key, allowedType[key])
resolve(typeof allowedType[key] === 'string')
} catch (error) {
reject(error)
}
}
})
}
function clickBtn () {
const fileInput = document.querySelector('#file')
console.log(fileInput.files)
fileType(fileInput.files[0]).then(res => {
console.log(res)
})
}