DIV CSS 佈局教程網

圖片上傳的格式驗證與即時預覽腳本實例
編輯:關於JavaScript     

圖片上傳時,除了後端驗證,前端若能即時檢查格式、大小並預覽效果,能大幅提升使用者體驗。以下提供一份兼顧 IE 與 Firefox 的完整腳本。

HTML 結構

<div id="imgbox">
  <img id="imghead" src="img/no_photo.gif" alt="" width="100" height="125" />
</div>
<asp:FileUpload ID="FileUploadImg" runat="server"
  onchange='previewImage(this);' style="position:relative;left:-130px;cursor:pointer;" />

格式驗證

var $$ = function(id) {
  return "string" == typeof id ? document.getElementById(id) : id;
};

function checkupload(ele) {
  var obj = $$("FileUploadImg");
  var fileContentType = obj.value.match(/^(.*)(\.)(.{1,8})$/)[3];
  if (fileContentType == 'gif' || fileContentType == 'jpeg'
      || fileContentType == 'png' || fileContentType == 'jpg') {
    return checkFileSize(ele); // 格式正確,接著驗證大小
  } else {
    alert('上傳文件格式不正確!');
    return false;
  }
}

大小驗證(跨瀏覽器)

function checkFileSize(ele) {
  var maxSize = 100 * 1024;
  if (window.navigator.userAgent.indexOf("MSIE") >= 1) { // IE
    try {
      var fso = new ActiveXObject('Scripting.FileSystemObject');
      var file = fso.GetFile(ele.value);
      return file.Size < maxSize;
    } catch (e) {
      alert("瀏覽器設置禁用 ActiveXObject 控件,請啟用");
      return false;
    }
  } else if (window.navigator.userAgent.indexOf("Firefox") >= 1) { // Firefox
    return ele.files[0].fileSize < maxSize;
  }
  return false;
}

即時預覽

function previewImage(ele) {
  if (ele && checkupload(ele)) {
    var imgDiv = $$("imgbox");
    imgDiv.innerHTML = "";
    imgDiv.style.width  = "100px";
    imgDiv.style.height = "125px";
    if (window.navigator.userAgent.indexOf("MSIE") >= 1) { // IE
      imgDiv.style.filter =
        "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod = scale)";
      imgDiv.filters("DXImageTransform.Microsoft.AlphaImageLoader").src = ele.value;
    } else if (window.navigator.userAgent.indexOf("Firefox") >= 1) { // Firefox
      imgDiv.innerHTML = "<img width='100' height='125' id='aPic' src='"
        + ele.files.item(0).getAsDataURL() + "'>";
    } else {
      imgDiv.innerHTML = "<span style='color:red;'>IE/火狐瀏覽器才支持圖片預覽</span>";
    }
  } else {
    $$("FileUploadImg").value = "";
    $$("imgbox").innerHTML =
      "<img id='imghead' src='img/no_photo.gif' alt='' width='100' height='125' />";
  }
}

重點整理

這份腳本示範了完整的圖片上傳前置處理流程:先用正則表達式從檔名取出副檔名做格式驗證,再驗證檔案大小,最後即時預覽。跨瀏覽器的處理是重點——IE 靠 ActiveX 的 FileSystemObject 取得檔案大小、用 AlphaImageLoader 做預覽;Firefox 則用 HTML5 的 File API(files[0] 與 getAsDataURL)來達成。

要提醒的是,这些方法今日已顯得老舊:IE 的 ActiveX 方案早已不可用,而現代瀏覽器普遍支援標準的 FileReader 物件,能更簡潔地讀取並預覽圖片。因此實際開發時,建議改用 FileReader.readAsDataURL 這種跨瀏覽器的標準做法,程式會更短、相容性也更好。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved