首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET MVC 整合 Uploadify 實現多文件上傳:前端配置與後端處理全流程

     編輯:關於ASP.NET

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>

後端 Controller Action

[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()

web.config 大檔案支援

<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>

現代替代方案

  • Dropzone.js:純 HTML5、無 Flash、拖拽上傳、圖片預覽、支援分塊上傳大檔案。
  • Fine Uploader:企業級、支援 S3 直傳、斷點續傳、圖片縮放。
  • 原生 <input type="file" multiple> + Fetch/XHR:零依賴、完全可控、配合 FormData、progress 事件。
  • ASP.NET Core:IFormFile、IFormFileCollection、內建 RequestSizeLimit 屬性、MultipartBodyLengthLimit 配置。

安全檢查清單

  • ✅ 副檔名白名單 + MIME 型別驗證 (fileInput1.ContentType)
  • ✅ 檔案大小雙重限制 (客戶端 + 伺服端)
  • ✅ 儲存路徑非 Web 可執行目錄 (或設定 HandlerMapping 禁用腳本執行)
  • ✅ 檔名隨機化 (Guid/Hash),拒絕使用者原始檔名
  • ✅ 上傳後病毒掃描 (ClamAV/Windows Defender)
  • ✅ 圖片重繪/去除 EXIF (防止圖片馬)
  • ✅ 速率限制 (IP/用戶/分鐘上傳數)
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved