萬盛學電腦網

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

JavaScript 本地圖片預覽:跨瀏覽器兼容實現指南

在表單提交前讓用戶即時看到選中的圖片,是提升用戶體驗的關鍵細節。但受限於瀏覽器安全策略,不同內核對本地文件讀取的支持差異極大。本文將系統梳理主流方案,並提供一個開箱即用的 ImagePreview 封裝,自動適配 IE6+、Firefox、Chrome、Safari、Opera 等環境。

瀏覽器支持現狀一覽

瀏覽器核心模式關鍵 API
IE 6/7/8Filter 模式AlphaImageLoader + selection.createRange()
Firefox 3.6+DOM File APIFileReader.readAsDataURL / URL.createObjectURL
Chrome / Safari / OperaRemote / DataURLFileReader、URL.createObjectURL、表單上傳回顯

統一封裝:ImagePreview 類

以下代碼已去除原始碼中的混淆壓縮部分,保留核心邏輯與註釋,方便二次開發:

/**
 * 統一圖片預覽組件
 * @param {HTMLInputElement} fileInput - type="file" 的 input 元素
 * @param {HTMLImageElement} imgTarget - 用於顯示預覽的 img 元素
 * @param {Object} options - 可選配置
 *   - mode: 'auto' | 'filter' | 'domfile' | 'remote' | 'simple'  強制指定模式
 *   - maxWidth, maxHeight: 預覽圖最大尺寸(px)
 *   - onCheck(file): 文件類型/大小校驗,返回 false 可攔截
 *   - onShow(dataURL): 預覽成功回調
 *   - onErr(msg): 失敗回調
 */
function ImagePreview(fileInput, imgTarget, options = {}) {
  this.file = fileInput;
  this.img = imgTarget;
  this._preload = null;
  this._data = '';
  this._upload = null;

  const opt = this._setOptions(options);
  this.action = opt.action;      // remote 模式上傳地址
  this.timeout = opt.timeout;    // remote 模式超時
  this.ratio = opt.ratio;        // 壓縮比例
  this.maxWidth = opt.maxWidth;
  this.maxHeight = opt.maxHeight;
  this.onCheck = opt.onCheck;
  this.onShow = opt.onShow;
  this.onErr = opt.onErr;

  // 根據模式綁定對應的數據獲取與顯示方法
  this._getData = this._getDataFun(opt.mode);
  this._show = opt.mode !== 'filter' ? this._simpleShow : this._filterShow;

  // 綁定 change 事件
  this.file.addEventListener('change', this._onChange.bind(this));
}

// 靜態屬性:自動檢測模式
ImagePreview.MODE = (() => {
  const ua = navigator.userAgent.toLowerCase();
  const isIE7 = /msie 7/.test(ua);
  const isIE8 = /msie 8/.test(ua);
  const isFF = /firefox/.test(ua);
  const isOpera = /opera/.test(ua);
  const isChrome = /chrome/.test(ua);
  const isSafari = /safari/.test(ua) && !isChrome;
  if (isIE7 || isIE8) return 'filter';
  if (isFF) return 'domfile';
  if (isOpera || isChrome || isSafari) return 'remote';
  return 'simple';
})();

// 透明佔位圖(解決 IE filter 模式下 src 為空報錯)
ImagePreview.TRANSPARENT = (() => {
  const ua = navigator.userAgent.toLowerCase();
  if (/msie (6|7)/.test(ua)) {
    const scripts = document.scripts;
    return 'mhtml:' + scripts[scripts.length - 1].src.replace(/[^\\/]*$/, '') + 'transparent.gif';
  }
  return 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';
})();

ImagePreview.prototype = {
  // 合併默認配置
  _setOptions(opt) {
    return Object.assign({
      mode: ImagePreview.MODE,
      action: '',
      timeout: 30000,
      ratio: 1,
      maxWidth: 800,
      maxHeight: 600,
      onCheck: () => true,
      onShow: () => {},
      onErr: () => {}
    }, opt);
  },

  // 文件選擇觸發
  _onChange(e) {
    const file = this.file.files?.[0] || this.file.value; // IE9- 只有 value
    if (!file) return;
    if (!this.onCheck(file)) return this.onErr('文件校驗不通過');
    this._getData(file);
  },

  // 根據模式返回數據獲取函數
  _getDataFun(mode) {
    switch (mode) {
      case 'domfile': return this._getDataDOMFile.bind(this);   // FileReader
      case 'filter':  return this._getDataFilter.bind(this);    // IE AlphaImageLoader
      case 'remote':  return this._getDataRemote.bind(this);    // 上傳後端返回 URL
      default:        return this._getDataSimple.bind(this);    // 直接用 value 做 src(極少數舊瀏覽器)
    }
  },

  // ---- 現代瀏覽器:FileReader ----
  _getDataDOMFile(file) {
    if (!window.FileReader) return this._getDataSimple(file);
    const reader = new FileReader();
    reader.onload = e => {
      this._data = e.target.result;
      this._show();
    };
    reader.onerror = () => this.onErr('文件讀取失敗');
    reader.readAsDataURL(file);
  },

  // ---- IE6-8:AlphaImageLoader Filter ----
  _getDataFilter(file) {
    // IE 無法直接獲取本地路徑,需用 selection.createRange() 取真實路徑
    this.file.select();
    const path = document.selection.createRange().text;
    this._data = path;
    this._show();
  },

  // ---- 遠程上傳模式 ----
  _getDataRemote(file) {
    const formData = new FormData();
    formData.append('file', file);
    const xhr = new XMLHttpRequest();
    xhr.timeout = this.timeout;
    xhr.onload = () => {
      if (xhr.status === 200) {
        try {
          const res = JSON.parse(xhr.responseText);
          this._data = res.url || res.data?.url;
          this._show();
        } catch {
          this.onErr('服務端返回格式錯誤');
        }
      } else {
        this.onErr(`上傳失敗:${xhr.status}`);
      }
    };
    xhr.onerror = () => this.onErr('網絡異常');
    xhr.ontimeout = () => this.onErr('上傳超時');
    xhr.open('POST', this.action);
    xhr.send(formData);
  },

  // ---- 降級:直接用 value ----
  _getDataSimple(file) {
    this._data = typeof file === 'string' ? file : file.value;
    this._show();
  },

  // ---- 通用顯示邏輯(現代瀏覽器)----
  _simpleShow() {
    this.img.onload = () => {
      URL.revokeObjectURL(this._data); // 釋放 Blob URL
      this.onShow(this._data);
    };
    this.img.onerror = () => this.onErr('圖片加載失敗');
    this.img.src = this._data;
  },

  // ---- IE Filter 顯示邏輯 ----
  _filterShow() {
    // 必須先設置尺寸,否則 filter 不生效
    this.img.style.width = this.maxWidth + 'px';
    this.img.style.height = this.maxHeight + 'px';
    this.img.style.filter = `progid:DXImageTransform.Microsoft.AlphaImageLoader(src='${this._data}', sizingMethod='scale')`;
    // 佔位 src 防止破圖圖標
    this.img.src = ImagePreview.TRANSPARENT;
    this.onShow(this._data);
  }
};

// ================= 使用示例 =================
/*
<input type="file" id="fileInput" accept="image/*">
<img id="preview" style="max-width:300px; max-height:200px;">

<script>
new ImagePreview(
  document.getElementById('fileInput'),
  document.getElementById('preview'),
  {
    mode: 'auto',
    maxWidth: 300,
    maxHeight: 200,
    onCheck(file) {
      if (!/^image\//.test(file.type)) return alert('請選擇圖片');
      if (file.size > 5 * 1024 * 1024) return alert('圖片不得超過 5MB');
      return true;
    },
    onShow(url) { console.log('預覽就緒:', url); },
    onErr(msg) { alert(msg); }
  }
);
</script>
*/

核心難點與解決方案

1. IE6-8 無法獲取真實文件路徑

早期 IE 出於安全考慮,input.value 僅返回虛擬路徑 C:\fakepath\xxx.jpg。解決方法是調用 input.select() 後,通過 document.selection.createRange().text 獲取真實路徑,再交給 AlphaImageLoader 渲染。

2. Filter 模式下圖片不按比例縮放

AlphaImageLoader 的 sizingMethod='scale' 會強制拉伸。需在 CSS 中給 img 固定 width/height,或在 JS 中根據原圖比例動態計算。

3. 內存洩漏防範

  • 使用 URL.createObjectURL 後務必在 onload 中 revokeObjectURL。
  • IE Filter 模式下,頁面卸載前建議將 img.style.filter = '' 釋放引用。

現代項目中的最佳實踐

若項目僅需支持現代瀏覽器(Edge 79+、Firefox 65+、Chrome 70+、Safari 13+),可直接使用 FileReader + DataURL 或 URL.createObjectURL,代碼極其簡潔:

const input = document.getElementById('fileInput');
const img = document.getElementById('preview');
input.addEventListener('change', () => {
  const file = input.files[0];
  if (!file || !/^image\//.test(file.type)) return;
  const url = URL.createObjectURL(file);
  img.onload = () => URL.revokeObjectURL(url);
  img.src = url;
});

對於需要兼容舊版 IE 的維護型項目,本文提供的 ImagePreview 類可直接引入使用;新項目建議採用現代 API,並配合 accept="image/*"、capture="environment" 等屬性提升移動端體驗。

copyright © 萬盛學電腦網 all rights reserved