DIV CSS 佈局教程網

jQuery 外掛 ajaxFileUpload 實戰:參數配置、常見錯誤與後端搭配
編輯:JQuery入門技巧     

ajaxFileUpload 不是什麼明星外掛,但它解決了一個很實際的問題:不刷新頁面、不用 Flash,就能異步上傳檔案。它的原理並不神秘——動態建立一個隱藏的 iframe 與 form,把檔案欄位塞進去提交,再從 iframe 取回結果。

要注意的是,網路上叫 ajaxFileUpload 的檔案非常多(畢竟自己寫一個也不難),彼此的實作細節並不相同。本文使用的是這份:https://github.com/carlcarl/AjaxFileUpload。如果你照著做卻出現「不是函式」這類錯誤,很可能就是版本對不上。

語法與參數

$.ajaxFileUpload([options]);

參數說明:

  • url — 處理上傳的伺服器端位址。
  • fileElementId — 要上傳的 file 欄位 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 — 檢查 file 欄位的 id 屬性是否存在。
  • SyntaxError: missing } in XML expression — 檢查 file 的 name 是否一致或根本沒設。
  • 其他自訂錯誤 — 直接把回傳的 $error 印出來看,比猜這些訊息快得多。

基本用法:四步驟完成異步上傳

第一步:引入 jQuery 與外掛。順序不能顛倒,所有 jQuery 外掛都是這個規矩。

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

第二步:HTML 結構。

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

第三步:前端 JS。

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

function ajaxFileUpload() {
    $.ajaxFileUpload({
        url: '/upload.aspx',        // 伺服器端處理位址
        secureuri: false,
        fileElementId: 'file1',     // 檔案欄位的 id
        dataType: 'json',           // 回傳型別,通常設 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;
}

第四步:後端 upload.aspx。

protected void Page_Load(object sender, EventArgs e) {
    HttpFileCollection files = Request.Files;
    string msg = string.Empty;
    string error = string.Empty;
    string 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();
    }
}

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;
            hfc[0].SaveAs(Server.MapPath(imgPath));
        }
        return Content(imgPath);
    }
}

前端把回傳的網址直接綁到 <img> 的 src:

$.ajaxFileUpload({
    url: '/Home/Upload',
    secureuri: false,
    fileElementId: 'file1',
    dataType: 'HTML',
    success: function (data, status) {
        alert(data);
        $("#img1").attr("src", data);
    },
    error: function (data, status, e) { alert(e); }
});

進階:上傳時一起帶參數

控制器用 Request.Form 取值,再用 Json() 一次回傳多個欄位:

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;
        hfc[0].SaveAs(Server.MapPath(imgPath));
    }
    // 注意 Json 的後面兩個參數不可省
    return Json(new { Id = nvc.Get("Id"), name = nvc.Get("name"), imgPath1 = imgPath },
                "text/html", JsonRequestBehavior.AllowGet);
}

前端在 options 裡加上 type 與 data:

$.ajaxFileUpload({
    url: '/Home/Upload',
    type: '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); }
});

三個用血淚換來的經驗

一、file 欄位一定要有 name。只給 id 不給 name,後端永遠收不到檔案。正確寫法是 <input type="file" id="file1" name="file1" />。

二、dataType 務必大寫。這個最經典的錯誤訊息是 Object function (a,b){...} has no method 'handleError',找上N次才定位到原因——把 dataType: 'HTML' 的 H 大寫就解決了。

三、版本要對得上。如果遇到 TypeError: $.ajaxFileUpload is not a function,幾乎可以確定你載入的 js 不是同一份。先確認檔案來源,再回頭查問題。

老實說,以今天的標準來看,這個外掛已經有點年紀了。新專案若無歷史包袱,直接用 FormData 搭配 $.ajax() 或 fetch() 會乾淨許多;但維護舊系統時,上面這些細節仍然值得記住。

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