ajaxfileupload.js 是輕量級 jQuery 非同步上傳插件,無需 Flash,透過隱藏 iframe 模擬 AJAX。本文提供前端 HTML/JS、後端 ASP.NET (ashx) 完整代碼。
jquery-2.1.1.js 與 ajaxfileupload.js<input id="fileToUpload" type="file" name="fileToUpload">
function saveCInfo() {
var filename = document.getElementById("fileToUpload").value;
if (filename != "") {
$.ajaxFileUpload({
url: '../Order/OrderExec.ashx?oprMode=fileUpload' +
"&filename=" + filename +
"&billno=" + billno +
"&companyname=" + companyname,
secureuri: false,
fileElementId: 'fileToUpload', // 上傳控件 ID
// dataType: 'json',
error: function() { alert('error'); },
success: function(datax) {
if (datax != "") {
msgShow('系統提示', '上傳成功!', 'info');
} else {
msgShow('系統提示', '上傳失敗!', 'info');
}
}
});
} else {
$.messager.alert('提示', '請選擇上傳檔案', 'info');
}
}
public void FileUpload(HttpContext context) {
try {
context.Response.ContentType = "text/html";
string companyname = context.Request.Params["companyname"];
string billno = context.Request.Params["billno"];
string filename = context.Request.Params["filename"];
string name = companyname + "_" + billno + "_" + filename;
HttpFileCollection files = HttpContext.Current.Request.Files;
string savePath = context.Server.MapPath("~/upload/");
if (!System.IO.Directory.Exists(savePath))
System.IO.Directory.CreateDirectory(savePath);
savePath += name;
files[0].SaveAs(savePath);
context.Response.Write(savePath);
} catch (Exception ex) {
context.Response.Write("FileUpload: " + ex.Message);
}
}
fileElementId:<input type="file"> 的 id 屬性url:可攜帶查詢字串傳遞額外參數secureuri:是否 HTTPS,通常 falsedataType:預期回應格式(json/xml/html/script)