export class FileType {
constructor() {
this.fs = wx.getFileSystemManager()
}
getType(filePath) {
let arrayBuffer = this.fs.readFileSync(filePath)
let uint8Array = new Uint8Array(arrayBuffer);
if (
this.checkString(uint8Array, 'ftyp', [4, 8]) &&
(uint8Array[8] & 0x60) !== 0x00
) {
return this.ftypTypeMate(uint8Array)
} else {
return ''
}
}
checkString(uint8Array, header, options) {
let arr = uint8Array.slice(...options)
let str = this.decimal2Ascll(arr)
return str == header
}
string2Bytes(string) {
return [...string].map(character => character.charCodeAt(0));
}
decimal2Ascll(uint8Array) {
let str = ''
for (let i = 0; i < uint8Array.length; i++) {
const decimal = uint8Array[i];
str += this.hex2ascll(this.decimal2hex(decimal))
}
return str
}
decimal2hex(val) {
return ("0" + (Number(val).toString(16))).slice(-2).toUpperCase()
}
hex2ascll(hexCharCodeStr) {
var trimedStr = hexCharCodeStr.trim();
var rawStr = trimedStr.substr(0, 2).toLowerCase() === "0x" ? trimedStr.substr(2) : trimedStr;
var len = rawStr.length;
if (len % 2 !== 0) {
console.error('存在非法字符!')
return "";
}
var curCharCode;
var resultStr = [];
for (var i = 0; i < len; i = i + 2) {
curCharCode = parseInt(rawStr.substr(i, 2), 16);
resultStr.push(String.fromCharCode(curCharCode));
}
return resultStr.join("");
}
ftypTypeMate(uint8Array) {
let extArray = uint8Array.slice(8, 12)
let extAscll = this.decimal2Ascll(extArray)
switch (extAscll) {
case 'avif':
case 'avis':
return {
ext: 'avif', mime: 'image/avif'
};
case 'mif1':
return {
ext: 'heic', mime: 'image/heif'
};
case 'msf1':
return {
ext: 'heic', mime: 'image/heif-sequence'
};
case 'heic':
case 'heix':
return {
ext: 'heic', mime: 'image/heic'
};
case 'hevc':
case 'hevx':
return {
ext: 'heic', mime: 'image/heic-sequence'
};
case 'qt':
return {
ext: 'mov', mime: 'video/quicktime'
};
case 'M4V':
case 'M4VH':
case 'M4VP':
return {
ext: 'm4v', mime: 'video/x-m4v'
};
case 'M4P':
return {
ext: 'm4p', mime: 'video/mp4'
};
case 'M4B':
return {
ext: 'm4b', mime: 'audio/mp4'
};
case 'M4A':
return {
ext: 'm4a', mime: 'audio/x-m4a'
};
case 'F4V':
return {
ext: 'f4v', mime: 'video/mp4'
};
case 'F4P':
return {
ext: 'f4p', mime: 'video/mp4'
};
case 'F4A':
return {
ext: 'f4a', mime: 'audio/mp4'
};
case 'F4B':
return {
ext: 'f4b', mime: 'audio/mp4'
};
case 'crx':
return {
ext: 'cr3', mime: 'image/x-canon-cr3'
};
default:
if (extAscll.startsWith('3g')) {
if (extAscll.startsWith('3g2')) {
return {
ext: '3g2',
mime: 'video/3gpp2'
};
}
return {
ext: '3gp',
mime: 'video/3gpp'
};
}
return {
ext: 'mp4', mime: 'video/mp4'
};
}
}
}