通过读取文件流判断文件是否是图片
当不能根据文件扩展名判断文件类型是,可以读取文件的内容来判断文件类型
var fileReader = new FileReader()
fileReader.onload = function () {
var array = this.result;
console.log("Array contains", array, isImage(new Uint8Array(array)), "bytes.", String.fromCharCode(...new Uint8Array(array)));
};
function ArrayBufferToString(buf) {
return String.fromCharCode(...new Uint16Array(buf))
}
var pngMagic = [
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a
];
var jpeg_jfif = [
0x4a, 0x46, 0x49, 0x46
];
var jpeg_exif = [
0x45, 0x78, 0x69, 0x66
];
var jpegMagic = [
0xFF, 0xD8, 0xFF, 0xE0
];
var gifMagic0 = [
0x47, 0x49, 0x46, 0x38, 0x37, 0x61
];
var getGifMagic1 = [
0x47, 0x49, 0x46, 0x38, 0x39, 0x61
];
function arraycopy(src, index, dist, distIndex, size) {
for (i = 0; i < size; i++) {
dist[distIndex + i] = src[index + i]
// console.log(src[index + i],index+i,src.length,'src')
}
console.log(dist, 'dist')
}
function arrayEquals(arr1, arr2) {
console.log(arr1)
console.log(arr2)
if (arr1 == 'undefined' || arr2 == 'undefined') {
return false
}
if (arr1 instanceof Array && arr2 instanceof Array) {
if (arr1.length != arr2.length) {
return false
}
for (i = 0; i < arr1.length; i++) {
if (arr1[i] != arr2[i]) {
return false
}
}
return true
}
return false;
}
function isImage(buf) {
if (buf == null || buf == 'undefined' || buf.length < 8) {
return null;
}
var bytes = [];
arraycopy(buf, 0, bytes, 0, 6);
if (isGif(bytes)) {
return "image/gif";
}
bytes = [];
arraycopy(buf, 6, bytes, 0, 4);
if (isJpeg(bytes)) {
return "image/jpeg";
}
bytes = [];
arraycopy(buf, 0, bytes, 0, 8);
if (isPng(bytes)) {
return "image/png";
}
return null;
}
/**
* @param data first 6 bytes of file
* @return gif image file true,other false
*/
function isGif(data) {
console.log('GIF')
return arrayEquals(data, gifMagic0) || arrayEquals(data, getGifMagic1);
}
/**
* @param data first 4 bytes of file
* @return jpeg image file true,other false
*/
function isJpeg(data) {
console.log('JPEG')
return arrayEquals(data, jpegMagic) || arrayEquals(data, jpeg_jfif) || arrayEquals(data, jpeg_exif);
}
/**
* @param data first 8 bytes of file
* @return png image file true,other false
*/
function isPng(data) {
console.log('PNG')
return arrayEquals(data, pngMagic);
}
/**
* 通过url获取blob
* @param url
* @param fileName
* @returns
*/
function getFileFromUrl(url, fileName) {
return new Promise((resolve, reject) => {
var blob = null;
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
// xhr.setRequestHeader('Accept', 'image/png');
xhr.responseType = "blob";
// 加载时处理
xhr.onload = () => {
// 获取返回结果
blob = xhr.response;
console.log(blob.toString())
fileReader.readAsArrayBuffer(blob);
let file = new File([blob], fileName);
// 返回结果
resolve(file);
};
xhr.onerror = (e) => {
reject(e)
};
// 发送
xhr.send();
});
}
getFileFromUrl('http://localhost/xxxxx', 'aa').then(res => {
console.log(res)
})