DIV CSS 佈局教程網

ajaxFileUpload 外掛完整解析:參數、錯誤訊息與三個實作範例
編輯:JavaScript綜合知識     

ajaxFileUpload 是一個 jQuery 的非同步檔案上傳外掛。本文把它的參數、常見錯誤的意義、以及從 Web Forms 到 ASP.NET MVC 的三種用法完整整理一遍。

語法與參數

$.ajaxFileUpload([options]);
  • url:上傳處理程式的位址。
  • fileElementId:檔案輸入域的 ID,即 <input type="file"> 的 id。
  • secureuri:是否啟用安全提交,預設 false。
  • dataType:伺服器回傳的資料類型,可為 xml、script、json、html。不填寫時 jQuery 會自行判斷。
  • success:成功後執行的函式,參數 data 是伺服器回傳的內容。
  • error:失敗時執行的函式。
  • data:自訂參數。當有額外資料要與檔案一起送出時很有用。
  • type:要提交自訂參數時,需設為 post。

常見錯誤訊息的真正含義

  • SyntaxError: missing ; before statement — 檢查 url 路徑是否可以正常存取。
  • SyntaxError: syntax error — 檢查後端處理程式本身是否有語法錯誤。
  • SyntaxError: invalid property id — 檢查文字域的 ID 屬性是否存在。
  • SyntaxError: missing } in XML expression — 檢查 file 元素的 name 是否一致或缺失。
  • Object function (a,b){...} has no method 'handleError' — 這個錯誤多半來自 dataType 的大小寫寫錯,例如寫成 'json' 而某些版本要求 'HTML'。

這些訊息之所以難懂,是因為外掛底層透過 iframe 取回應,任何格式不符都會在 eval 階段炸開,而非丟出有意義的錯誤。除錯時最快的做法是在 error 回呼中直接把回傳內容印出來看:

error: function (data, status, e) {
    console.log(data, status, e);
}

範例一:Web Forms 基本用法

先引入外掛(順序不可顛倒):

<script src="jquery-1.7.1.js" type="text/javascript"></script>
<script src="ajaxfileupload.js" type="text/javascript"></script>

HTML:

<p><input type="file" id="file1" name="file" /></p>
<input type="button" value="上傳" />
<p><img id="img1" alt="上傳成功啦" src="" /></p>

JavaScript:

$(function () {
    $(":button").click(function () {
        ajaxFileUpload();
    });
});

function ajaxFileUpload() {
    $.ajaxFileUpload({
        url: '/upload.aspx',            // 伺服器端處理位址
        secureuri: false,
        fileElementId: 'file1',         // 檔案域的 ID
        dataType: 'json',               // 回傳值類型
        success: function (data, status) {
            $("#img1").attr("src", data.imgurl);
            if (typeof (data.error) != 'undefined') {
                if (data.error != '') { alert(data.error); }
                else { alert(data.msg); }
            }
        },
        error: function (data, status, e) {
            alert(e);
        }
    });
    return false;
}

後端:

protected void Page_Load(object sender, EventArgs e)
{
    HttpFileCollection files = Request.Files;
    string msg = string.Empty, error = string.Empty, imgurl;

    if (files.Count > 0)
    {
        files[0].SaveAs(Server.MapPath("/") + System.IO.Path.GetFileName(files[0].FileName));
        msg    = " 成功! 檔案大小為:" + files[0].ContentLength;
        imgurl = "/" + files[0].FileName;

        string res = "{ error:'" + error + "', msg:'" + msg + "',imgurl:'" + imgurl + "'}";
        Response.Write(res);
        Response.End();
    }
}

範例二:ASP.NET MVC 版本

控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Upload()
    {
        HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
        string imgPath = "";

        if (hfc.Count > 0)
        {
            imgPath = "/testUpload" + hfc[0].FileName;
            string physicalPath = Server.MapPath(imgPath);
            hfc[0].SaveAs(physicalPath);
        }
        return Content(imgPath);
    }
}

前端在成功回呼中把傳回的路徑綁到 img 的 src:

success: function (data, status) {
    alert(data);
    $("#img1").attr("src", data);
}

注意這裡 dataType 設為 'HTML' 而非 json——因為 Content() 回傳的是純字串。這正是上面提到的「dataType 大小寫與類型必須對應」的實例。

範例三:附帶自訂參數

控制器:

public ActionResult Upload()
{
    NameValueCollection nvc = System.Web.HttpContext.Current.Request.Form;
    HttpFileCollection  hfc = System.Web.HttpContext.Current.Request.Files;
    string imgPath = "";

    if (hfc.Count > 0)
    {
        imgPath = "/testUpload" + hfc[0].FileName;
        string physicalPath = Server.MapPath(imgPath);
        hfc[0].SaveAs(physicalPath);
    }

    return Json(new {
        Id       = nvc.Get("Id"),
        name     = nvc.Get("name"),
        imgPath1 = imgPath
    }, "text/html", JsonRequestBehavior.AllowGet);
}

前端加上 data 與 type:

$.ajaxFileUpload({
    url: '/Home/Upload',
    type: 'post',                                  // 有自訂參數就必須是 post
    data: { Id: '123', name: 'lunis' },            // 引號寫錯一個都會失敗
    secureuri: false,
    fileElementId: 'file1',
    dataType: 'json',
    success: function (data, status) {
        $("#img1").attr("src", data.imgPath1);
        alert("你請求的 Id 是" + data.Id + " 你請求的名字是:" + data.name);
    },
    error: function (data, status, e) { alert(e); }
});

兩個實測才發現的坑

檔案域必須有 name 屬性。只寫 id 不寫 name,畫面上選得到檔案、程式也不報錯,但伺服器端永遠收不到檔案。正確寫法是 <input type="file" id="file1" name="file1" />。

dataType 要對應回傳方式。控制器用 Content() 回字串就該寫 'HTML',用 Json() 就寫 'json'。寫錯不會有清楚錯誤,只會出現那個莫名的 handleError 訊息。

安全提醒

範例中把 hfc[0].FileName 直接接進儲存路徑,這有兩層風險:檔名可能含 ..\ 造成任意位置寫入,且未驗證副檔名可能導致上傳可執行的腳本檔。正式環境請務必:用 Path.GetFileName() 清掉路徑部分、以副檔名白名單驗證、自行產生儲存名稱(不沿用使用者檔名)、並確認上傳目錄禁止執行。

現況說明

ajaxFileUpload 的原理是建立隱藏 iframe 讓表單 post 到它,再從中取出回應——因此它無法回報真實進度,也無法在舊瀏覽器之外正常運作。今天要實作非同步上傳,FormData 加 fetch 或 XMLHttpRequest 就足夠,並能透過 upload.onprogress 取得真正的百分比進度:

var xhr = new XMLHttpRequest();
xhr.upload.onprogress = function (e) {
    if (e.lengthComputable) {
        console.log(Math.round(e.loaded / e.total * 100) + "%");
    }
};
xhr.open("POST", "/Home/Upload");
xhr.send(formData);
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved