ajaxFileUpload 是一個 jQuery 的非同步檔案上傳外掛。本文把它的參數、常見錯誤的意義、以及從 Web Forms 到 ASP.NET MVC 的三種用法完整整理一遍。
$.ajaxFileUpload([options]);
<input type="file"> 的 id。post。'json' 而某些版本要求 'HTML'。這些訊息之所以難懂,是因為外掛底層透過 iframe 取回應,任何格式不符都會在 eval 階段炸開,而非丟出有意義的錯誤。除錯時最快的做法是在 error 回呼中直接把回傳內容印出來看:
error: function (data, status, e) {
console.log(data, status, e);
}
先引入外掛(順序不可顛倒):
<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();
}
}
控制器:
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);