$.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>
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); // 回傳圖片相對路徑
}
}
<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>
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' 即可傳遞。