DIV CSS 佈局教程網

自己動手做 Ajax 圖片上傳:兩種方案與相容性比較
編輯:AJAX基礎知識     

網上現成的圖片上傳元件不少,但真正符合自己需求又順手的卻不多,於是決定自己寫一個。以下記錄兩種做法,以及各自的相容性限制。

方法一:純 jQuery 搭配 FormData

<p>
<label>上傳圖片</label>
<input class="ke-input-text" type="text" id="url" value="" readonly="readonly" />
<input type="button" id="uploadButton" value="Upload" />
</p>

<script type="text/javascript">
$(function () {
    $('.inp_fileToUpload').change(function () {
        var formdata = new FormData();
        var v_this = $(this);
        var fileObj = v_this.get(0).files;
        var url = "/upload/upload_json.ashx";

        formdata.append("imgFile", fileObj[0]);

        jQuery.ajax({
            url: url,
            type: 'post',
            data: formdata,
            cache: false,
            contentType: false,
            processData: false,
            dataType: "json",
            success: function (data) {
                if (data.error == 0) {
                    v_this.parent().children(".img_upload").attr("src", data.url);
                }
            }
        });
        return false;
    });
});
</script>

這裡有三個關鍵設定:contentType: false 讓瀏覽器自行產生含 boundary 的 multipart 標頭,processData: false 則避免 jQuery 把 FormData 轉成字串。少了任何一個,上傳都會失敗。

缺點:IE9 及以下版本不支援 FormData,所以這個方法無法相容舊版 IE。

方法二:使用 ajaxfileupload.js

<p>
<label>ajax 上傳</label>
<input type="file" name="fileToUpload" id="fileToUpload"
       class="inp_fileToUpload" multiple="multiple" />
<img src="images/lb_head.jpg" width="30px" height="30px"
     class="img_upload" id="img" />
</p>

<script type="text/javascript">
$(function () {
    $(".inp_fileToUpload").live("change", function () {
        ajaxFileUpload($(this).attr("id"),
                       $(this).parent().children(".img_upload").attr("id"));
    });
});

function ajaxFileUpload(file_id, img_id) {
    jQuery.ajaxFileUpload({
        url: '/upload/upload_json.ashx',   // 伺服器端接收位址
        secureuri: false,                  // 是否需要安全協議
        fileElementId: file_id,            // 檔案欄位的 ID
        dataType: 'json',                  // 回傳值類型
        success: function (data, status) {
            if (data.error == 0) {
                $("#" + img_id).attr("src", data.url);
            } else {
                alert(data.message);
            }
        },
        error: function (data, status, e) {
            alert(e);
        }
    });
    return false;
}
</script>

這個做法的底層其實是把表單塞進隱藏的 iframe 再提交,藉此達到「看起來像非同步」的效果。實測可支援 IE8/9 與 Chrome,相容性明顯優於方法一,因此建議採用。

後端處理(ASP.NET)

<%@ WebHandler Language="C#" Class="Upload" %>
using System;
using System.Collections;
using System.Web;
using System.IO;
using System.Globalization;
using LitJson;

public class Upload : IHttpHandler {

    private HttpContext context;

    public void ProcessRequest(HttpContext context) {
        String aspxUrl = context.Request.Path.Substring(0,
            context.Request.Path.LastIndexOf("/") + 1);
        String savePath = "attached/";        // 實體目錄
        String saveUrl  = aspxUrl + "attached/";  // 對應網址

        // 允許的副檔名
        Hashtable extTable = new Hashtable();
        extTable.Add("image", "gif,jpg,jpeg,png,bmp");
        extTable.Add("flash", "swf,flv");
        extTable.Add("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
        extTable.Add("file",  "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");

        int maxSize = 1000000;   // 大小上限
        this.context = context;

        HttpPostedFile imgFile = context.Request.Files["imgFile"];
        if (imgFile == null) { showError("請選擇檔案。"); }

        String dirPath = context.Server.MapPath(savePath);
        if (!Directory.Exists(dirPath)) { showError("上傳目錄不存在。"); }

        String dirName = context.Request.QueryString["dir"];
        if (String.IsNullOrEmpty(dirName)) { dirName = "image"; }
        if (!extTable.ContainsKey(dirName)) { showError("目錄名不正確。"); }

        String fileExt = Path.GetExtension(imgFile.FileName).ToLower();
        if (imgFile.InputStream == null || imgFile.InputStream.Length > maxSize) {
            showError("上傳檔案大小超過限制。");
        }
        if (String.IsNullOrEmpty(fileExt) ||
            Array.IndexOf(((String)extTable[dirName]).Split(','),
                          fileExt.Substring(1).ToLower()) == -1) {
            showError("不允許的副檔名,只允許 " + ((String)extTable[dirName]) + " 格式。");
        }

        // 依日期建立子目錄
        dirPath += dirName + "/";
        saveUrl += dirName + "/";
        if (!Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath); }

        String ymd = DateTime.Now.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo);
        dirPath += ymd + "/";
        saveUrl += ymd + "/";
        if (!Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath); }

        String newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff",
            DateTimeFormatInfo.InvariantInfo) + fileExt;
        imgFile.SaveAs(dirPath + newFileName);

        Hashtable hash = new Hashtable();
        hash["error"] = 0;
        hash["url"] = saveUrl + newFileName;
        context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
        context.Response.Write(JsonMapper.ToJson(hash));
        context.Response.End();
    }

    private void showError(string message) {
        Hashtable hash = new Hashtable();
        hash["error"] = 1;
        hash["message"] = message;
        context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
        context.Response.Write(JsonMapper.ToJson(hash));
        context.Response.End();
    }

    public bool IsReusable { get { return true; } }
}

後端設計的幾個要點

副檔名白名單是基本防線。只允許清單內的型別,並把檔案重新命名為時間戳,避免使用者上傳 .aspx 或 .php 這類可執行腳本。同時也應檢查檔案的實際內容型別(magic number),因為副檔名是可以偽造的。

目錄不可執行。上傳目錄最好設定為禁止執行腳本,這樣即使木馬檔案成功落地,也無法被觸發。

回應標頭。由於 ajaxFileUpload 底層用 iframe,回應必須是 HTML 而非 application/json,否則部分瀏覽器會提示下載檔案。

最後補充:範例中的 .live() 在 jQuery 1.9 之後已被移除,新專案請改用 $(document).on('change', '.inp_fileToUpload', ...) 的事件委派寫法。

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