JavaScript中如何判断文件类型

355 阅读1分钟

一、基于文件后缀名的判断

文件后缀名是文件类型的一种常见标识。在JavaScript中判断文件类型,可以通过判断文件后缀名的方式进行。具体实现步骤如下:

function checkFileType(fileName) {
  let fileExtension = fileName.split('.').pop().toLowerCase();
  let fileTypes = {
    'jpg': 'image/jpeg',
    'jpeg': 'image/jpeg',
    'png': 'image/png',
    'gif': 'image/gif',
    'bmp': 'image/bmp',
    'pdf': 'application/pdf',
    'doc': 'application/msword',
    'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'xls': 'application/vnd.ms-excel',
    'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'ppt': 'application/vnd.ms-powerpoint',
    'pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation'
  };
  if (fileTypes[fileExtension]) {
    return fileTypes[fileExtension];
  } else {
    return false;
  }
}

二、基于文件头部的判断

文件头部是文件的一段特定字节序列,在文件中距离文件开始处的位置固定。通过查看文件头部,我们可以判断文件的类型。具体实现步骤如下:

function checkFileType(file) {
  let fileType = '';
  const reader = new FileReader();
  reader.onloadend = function(event) {
    const arr = (new Uint8Array(event.target.result)).subarray(0, 4);
    let header = '';
    for (let i = 0; i < arr.length; i++) {
      header += arr[i].toString(16);
    }
    switch (header) {
      case '89504e47':
        fileType = 'image/png';
        break;
      case '47494638':
        fileType = 'image/gif';
        break;
      case 'ffd8ffe0':
      case 'ffd8ffe1':
      case 'ffd8ffe2':
        fileType = 'image/jpeg';
        break;
      case '25504446':
        fileType = 'application/pdf';
        break;
      case '504b34':
        fileType = 'application/zip';
        break;
      default:
        fileType = false;
        break;
    }
  };
  reader.readAsArrayBuffer(file);
  return fileType;
}

三、基于Magic Number的判断

Magic Number(魔法数)是一段文件开头的固定字节序列。通过判断文件的 Magic Number,我们可以进一步确认文件的类型。具体实现步骤如下:

function checkFileType(file, callback) {
  const reader = new FileReader();
  reader.onloadend = function(event) {
    const fileContent = event.target.result;
    const magicNumber = fileContent.slice(0, 4);
    let fileType = '';
    switch(magicNumber) {
      case 'BM':
        fileType = 'image/bmp';
        break;
      case '\x89PNG':
        fileType = 'image/png';
        break;
      case 'GIF8':
        fileType = 'image/gif';
        break;
      case 'JV':
        fileType = 'image/pjpeg';
        break;
      case '%PDF':
        fileType = 'application/pdf';
        break;
      case '\x50\x4B\x03\x04':
        fileType = 'application/zip';
        break;
      default:
        fileType = false;
        break;
    }
    callback(fileType);
  };
  reader.readAsBinaryString(file.slice(0, 4));
}