上傳檔案時能即時看到進度,使用者體驗會好很多。本文示範如何使用 Uploadify 這個 jQuery 插件,搭配 ASP.NET 後端,做出帶有進度條的多檔上傳功能。
先引入 Uploadify 相關的 CSS 與 JS,再初始化插件,設定上傳路徑、檔案類型、大小限制等參數:
$("#uploadify").uploadify({
'uploader': 'js/jquery.uploadify-v2.1.4/uploadify.swf',
'script': 'UploadHandler.ashx',
'folder': 'UploadFile/<% = subpathName %>',
'queueID': 'fileQueue',
'auto': false,
'multi': true,
'fileExt': '*.jpg;*.gif;*.png',
'sizeLimit': 102400,
'onComplete': function (event, ID, fileObj, response, data) {
alert('There are ' + data.fileCount + ' files remaining in the queue.');
}
});
页面再擺上 fileQueue 容器、file 輸入框與上傳、取消的連結即可。
後端用ashx 一般處理常式接收檔案,判斷資料夾是否存在、不存在則建立,再存檔:
HttpPostedFile file = context.Request.Files["Filedata"];
string uploadPath = HttpContext.Current.Server.MapPath(@context.Request["folder"]);
if (file != null){
if (!Directory.Exists(uploadPath)){
Directory.CreateDirectory(uploadPath);
}
file.SaveAs(Path.Combine(uploadPath, file.FileName));
context.Response.Write("1");
}
透過 Uploadify 內建的進度條與事件回呼,就能清楚掌握每個檔案的上傳狀況。