萬盛學電腦網

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

jQuery 非同步上傳插件 ajaxFileUpload 參數詳解與 MVC 實戰範例

$.ajaxFileUpload(options) 是經典的 jQuery 非同步上傳外掛。本文系統整理參數、常見錯誤代碼、基本用法、ASP.NET MVC 整合、帶參數上傳三大場景。

參數完整說明

參數說明
url上傳處理器網址
fileElementId<input type="file"> 的 id
secureuri是否啟用安全協定,預設 false
dataType回應資料類型:xml/script/json/html,不填自動判斷
success成功回調,參數 data 為伺服器回傳資料
error失敗回調
data自訂額外參數(需配合 type: 'post')
type傳遞 data 時必須設為 'post'

常見錯誤代碼對照

  • SyntaxError: missing ; before statement → url 路徑無法存取
  • SyntaxError: syntax error → 後端處理器語法錯誤
  • SyntaxError: invalid property id → fileElementId 不存在
  • SyntaxError: missing } in XML expression → 檔案 name 屬性不一致或缺失
  • 建議直接在後端印出變數除錯,比瀏覽器錯誤訊息更直觀

基本用法範例

<script src="jquery-1.7.1.js"></script>
<script src="ajaxfileupload.js"></script>
<script>
$(function(){
    $(":button").click(function(){ ajaxFileUpload(); });
});
function ajaxFileUpload() {
    $.ajaxFileUpload({
        url: '/upload.aspx',
        secureuri: false,
        fileElementId: 'file1',
        dataType: 'json',
        success: function(data, status) {
            $("#img1").attr("src", data.imgurl);
            if (typeof data.error != 'undefined') {
                alert(data.error != '' ? data.error : data.msg);
            }
        },
        error: function(data, status, e) { alert(e); }
    });
    return false;
}
</script>

ASP.NET MVC 控制器

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

    public ActionResult Upload() {
        var 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); // 回傳圖片相對路徑
    }
}

MVC 視圖(HTML + JS)

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

<script>
$(function(){
    $(":button").click(function(){
        if ($("#file1").val().length > 0) ajaxFileUpload();
        else alert("請選擇圖片");
    });
});
function ajaxFileUpload() {
    $.ajaxFileUpload({
        url: '/Home/Upload',
        secureuri: false,
        fileElementId: 'file1',
        dataType: 'html', // MVC 回傳 Content(string)
        success: function(data) {
            alert(data);
            $("#img1").attr("src", data);
        },
        error: function(data, status, e) { alert(e); }
    });
    return false;
}
</script>

帶額外參數上傳(MVC)

public ActionResult Upload() {
    var nvc = System.Web.HttpContext.Current.Request.Form;
    var 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 必須指定 contentType 與 JsonRequestBehavior
    return Json(new {
        Id = nvc.Get("Id"),
        name = nvc.Get("name"),
        imgPath1 = imgPath
    }, "text/html", JsonRequestBehavior.AllowGet);
}

前端 data: { Id: 123, name: "test" }, type: 'post' 即可傳遞。

copyright © 萬盛學電腦網 all rights reserved