萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 檔案上傳驗證:限制圖片類型、大小與檔名安全的完整實作

前端檔案上傳前的驗證是「第一道防線」,雖然後端必須再驗證,但良好的前端攔截能大幅降低伺服器負載並即時回饋使用者。本文提供一個完整、可複用的驗證模組,涵蓋副檔名白名單、MIME 型別檢查、檔案大小限制、檔名清理、多檔案批次驗證。

核心驗證邏輯


/**
 * 檔案上傳驗證器
 * @param {Object} options
 *   - accept: string[] 允許的副檔名 (不含點) 如 ['jpg','png','gif','webp']
 *   - mimeTypes: string[] 允許的 MIME 型別 如 ['image/jpeg','image/png','image/gif','image/webp']
 *   - maxSize: number 最大位元組數 (預設 5MB)
 *   - maxFiles: number 最大檔案數 (預設 10)
 *   - sanitizeFileName: boolean 是否清理檔名 (預設 true)
 */
class FileUploadValidator {
  constructor(options = {}) {
    this.accept = new Set((options.accept || ['jpg','jpeg','png','gif','webp']).map(e => e.toLowerCase()));
    this.mimeTypes = new Set(options.mimeTypes || ['image/jpeg','image/png','image/gif','image/webp']);
    this.maxSize = options.maxSize || 5 * 1024 * 1024; // 5MB
    this.maxFiles = options.maxFiles || 10;
    this.sanitize = options.sanitizeFileName !== false;
  }

  /** 驗證單一 File 物件 */
  validate(file) {
    const errors = [];
    
    // 1. 副檔名
    const ext = file.name.split('.').pop()?.toLowerCase() || '';
    if (!this.accept.has(ext)) {
      errors.push(`不支援的副檔名: .${ext} (允許: ${[...this.accept].join(', ')})`);
    }

    // 2. MIME 型別(瀏覽器提供,但可被偽造,僅作初步篩選)
    if (!this.mimeTypes.has(file.type)) {
      errors.push(`不支援的檔案類型: ${file.type || 'unknown'} (允許: ${[...this.mimeTypes].join(', ')})`);
    }

    // 3. 檔案大小
    if (file.size > this.maxSize) {
      errors.push(`檔案過大: ${this._formatSize(file.size)} (上限: ${this._formatSize(this.maxSize)})`);
    }

    // 4. 檔名安全性
    if (this.sanitize && this._hasRiskyChars(file.name)) {
      errors.push('檔名包含風險字元,已自動清理');
    }

    return {
      valid: errors.length === 0,
      errors,
      sanitizedName: this.sanitize ? this._sanitize(file.name) : file.name
    };
  }

  /** 批次驗證 FileList 或 File 陣列 */
  validateAll(files) {
    const fileArr = Array.from(files);
    if (fileArr.length > this.maxFiles) {
      return { valid: false, errors: [`一次最多上傳 ${this.maxFiles} 個檔案`], results: [] };
    }
    const results = fileArr.map(f => this.validate(f));
    const allValid = results.every(r => r.valid);
    return { valid: allValid, errors: results.flatMap(r => r.errors), results };
  }

  _formatSize(bytes) {
    if (bytes < 1024) return `${bytes} B`;
    const k = bytes < 1024**2 ? 1 : bytes < 1024**3 ? 2 : 3;
    const unit = ['KB','MB','GB'][k-1];
    return (bytes / 1024**k).toFixed(1) + ' ' + unit;
  }

  _hasRiskyChars(name) {
    // 檢測路徑遍歷、控制字元、保留字元等
    return /[<>:"|?*\x00-\x1F]/.test(name) || /\.\./.test(name) || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i.test(name.split('.')[0]);
  }

  _sanitize(name) {
    return name
      .replace(/[<>:"|?*\x00-\x1F]/g, '_') // 非法字元替換
      .replace(/\.\.+/g, '.')               // 移除路徑遍歷
      .replace(/^\.+/, '')                  // 移除開頭點
      .substring(0, 255);                   // 限制長度
  }
}

// 導出 (ESM/CommonJS 通用)
if (typeof module !== 'undefined') module.exports = FileUploadValidator;

前端整合範例(原生 + jQuery 双版本)

原生 JS 版


const validator = new FileUploadValidator({ maxSize: 2 * 1024 * 1024 }); // 2MB

document.getElementById('fileInput').addEventListener('change', async (e) => {
  const { valid, errors, results } = validator.validateAll(e.target.files);
  
  if (!valid) {
    alert('驗證失敗:\n' + errors.join('\n'));
    e.target.value = ''; // 清空選擇
    return;
  }

  // 全部通過,顯示預覽或上傳
  for (const { sanitizedName, valid } of results) {
    if (!valid) continue;
    // 建立預覽...
  }
});

jQuery 版(對應原文風格)


const validator = new FileUploadValidator();

$('input[type="file"]').on('change', function () {
  const { valid, errors, results } = validator.validateAll(this.files);
  
  if (!valid) {
    alert(errors.join('\n'));
    $(this).val(''); // 清空
    return;
  }

  // 顯示預覽縮圖
  const $preview = $('#preview').empty();
  results.forEach(({ sanitizedName }) => {
    const file = Array.from(this.files).find(f => validator._sanitize(f.name) === sanitizedName);
    if (file && file.type.startsWith('image/')) {
      const url = URL.createObjectURL(file);
      $preview.append(`${sanitizedName}`);
    }
  });
});

進階:結合 FileReader 進行內容級驗證(Magic Number)

副檔名與 MIME 皆可偽造,真正安全需讀取檔案頭部位元組:


const MAGIC_NUMBERS = {
  'image/jpeg': [0xFF, 0xD8, 0xFF],
  'image/png': [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A],
  'image/gif': [0x47, 0x49, 0x46, 0x38], // GIF87a / GIF89a
  'image/webp': [0x52, 0x49, 0x46, 0x46] // RIFF...WEBP (需進一步確認)
};

async function checkMagicNumber(file, expectedMime) {
  const signature = MAGIC_NUMBERS[expectedMime];
  if (!signature) return true; // 無特徵碼則跳過
  
  const buffer = await file.slice(0, signature.length).arrayBuffer();
  const bytes = new Uint8Array(buffer);
  return signature.every((b, i) => b === bytes[i]);
}

// 在 validate() 中加入
// const magicOk = await checkMagicNumber(file, file.type);
// if (!magicOk) errors.push('檔案內容與宣稱類型不符,可能偽造');

安全性檢查清單

  • ✅ 副檔名白名單(非黑名單)
  • ✅ MIME 型別白名單
  • ✅ 檔案大小上限
  • ✅ 檔案數量上限
  • ✅ 檔名清理(移除路徑遍歷、控制字元、Windows 保留名)
  • ✅ Magic Number 內容驗證(高安全需求)
  • ✅ 後端二次驗證(不可省略)
  • ✅ 上傳目錄不可執行腳本
  • ✅ 亂數重命名儲存(避免覆蓋、路徑遍歷)
  • ✅ 病毒掃描整合(ClamAV 等)

結語

前端驗證是為了「使用者體驗」與「減輕後端壓力」,絕非安全邊界。請將 FileUploadValidator 納入專案共用庫,並根據業務調整白名單與大小限制。記住:永遠不要信任前端傳來的任何資料,後端必須完整重新驗證。

copyright © 萬盛學電腦網 all rights reserved