MVC 無內建上傳控件,引入 jQuery Uploadify (Flash/HTML5 雙模) 快速實現多文件選擇、進度條、佇列管理。本文涵蓋前端初始化、後端 Action、路由、大小限制、錯誤處理完整流程。
<script src="~/Scripts/jquery-1.4.1.min.js"></script>
<script src="~/Scripts/swfobject.js"></script>
<script src="~/Scripts/jquery.uploadify.v2.1.0.min.js"></script>
<link href="~/Content/uploadify.css" rel="stylesheet" />
下載地址:uploadify.com
<input id="fileInput1" name="fileInput1" type="file" />
<a href="javascript:if(checkLoad()){$('#fileInput1').uploadifySettings('scriptData',{'name':$('#test').val()});$('#fileInput1').uploadifyUpload();}">上傳</a>
<span id="result"></span>
<script>
$(function () {
$('#fileInput1').uploadify({
'uploader': '/Content/uploadify.swf', // Flash 上傳組件
'script': '/Home/LoadFile', // 後端 Action 路由
'folder': '/UploadFiles', // 伺服器儲存相對路徑 (舊版參數)
'cancelImg': '/Content/cancel.png',
'sizeLimit': 1024 * 1024 * 4, // 4MB
'multi': true, // 多文件
'onComplete': Complete, // 單文件完成回調
'onAllComplete': function(event, data) { // 全部完成
showInfo(`全部完成:上傳 ${data.filesUploaded} 個`, true);
},
'onError': function(event, queueId, fileObj, errorObj) {
showInfo(`錯誤:${fileObj.name} - ${errorObj.type}`, false);
}
});
});
function Complete(event, queueID, fileObj, response, data) {
if (response != "") showInfo("成功上傳 " + response, true);
else showInfo("文件上傳出錯!", false);
}
function showInfo(msg, type) {
$("#result").removeClass().addClass(type ? "SuccessText" : "FaileText").html(msg);
}
function checkLoad() {
if ($.trim($('#fileInput1Queue').html()) == "") { alert('請先選擇要上傳的文件!'); return false; }
return true;
}
</script>
[HttpPost]
public ActionResult LoadFile(HttpPostedFileBase fileInput1, string name) {
if (fileInput1 == null || fileInput1.ContentLength == 0)
return Content(""); // Uploadify 期望回傳空字串表示失敗
// 1. 驗證副檔名、MIME、大小 (雙重防護)
var allowedExt = new[] { ".jpg", ".png", ".pdf", ".docx" };
var ext = Path.GetExtension(fileInput1.FileName).ToLower();
if (!allowedExt.Contains(ext)) return Content("類型不允許");
// 2. 生成唯一檔名,防覆蓋、防路徑遍歷
var fileName = $"{Guid.NewGuid()}{ext}";
var savePath = Server.MapPath("~/UploadFiles");
if (!Directory.Exists(savePath)) Directory.CreateDirectory(savePath);
var fullPath = Path.Combine(savePath, fileName);
// 3. 儲存
fileInput1.SaveAs(fullPath);
// 4. 記錄資料庫、掃描病毒、生成縮圖... (異步隊列)
return Content(fileName); // 回傳給 onComplete 的 response 參數
}
| 參數 | 說明 | 注意 |
|---|---|---|
script | 上傳處理 URL | 需對應 Controller/Action,區分大小寫 |
scriptData | 額外表單參數 | 動態設定:uploadifySettings('scriptData', {...}) |
sizeLimit | 客戶端檔案大小限制 (bytes) | 伺服端 web.config <httpRuntime maxRequestLength> 必須更大 |
fileExt | 允許副檔名 | 如 '*.jpg;*.png;*.pdf',客戶端攔截 |
fileDesc | 檔案類型描述 | 選擇對話框顯示 |
auto | 選擇後自動上傳 | false 需手動觸發 uploadifyUpload() |
<system.web>
<!-- maxRequestLength 单位 KB,這裡 100MB -->
<httpRuntime maxRequestLength="102400" executionTimeout="300" />
</system.web>
<system.webServer>
<!-- IIS 7+ 单位 bytes -->
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="104857600" />
</requestFiltering>
</security>
</system.webServer>
<input type="file" multiple> + Fetch/XHR:零依賴、完全可控、配合 FormData、progress 事件。IFormFile、IFormFileCollection、內建 RequestSizeLimit 屬性、MultipartBodyLengthLimit 配置。fileInput1.ContentType)HandlerMapping 禁用腳本執行)