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

ASP.NET MVC 文件上傳即時驗證:Uploadify 整合 ImageUtility 實現前端攔截非圖片

     編輯:關於ASP.NET

業務痛點

上一篇實現了服務端驗證,但用戶上傳非圖片時仍需等待上傳完成才收到錯誤,體驗差。需在客戶端選擇文件瞬間攔截非圖片,取消上傳並提示。

ImageUtility 新增重載

public static bool IsImage(HttpPostedFileBase file) {
    if (file == null || file.ContentLength == 0) return false;
    using (Stream stream = file.InputStream) {
        byte[] header = new byte[8];
        stream.Read(header, 0, 8);
        stream.Position = 0; // 重置流位置,供後續保存讀取
        return CheckSignature(header);
    }
}

控制器上傳 Action

[HttpPost]
public ActionResult Upload(HttpPostedFileBase fileData) {
    if (!ImageUtility.IsImage(fileData)) {
        return Json(new { success = false, msg = "請選擇圖片文件" });
    }
    // 保存邏輯...
    return Json(new { success = true, path = savedPath });
}

Uploadify 前端配置關鍵點

$('#file_upload').uploadify({
    'swf': '/Scripts/uploadify.swf',
    'uploader': '/Controller/Upload',
    'fileTypeDesc': '圖片文件',
    'fileTypeExts': '*.jpg;*.jpeg;*.png;*.gif;*.bmp',
    'onSelect': function(file) {
        // 可選:客戶端再次檢查擴展名
    },
    'onUploadSuccess': function(file, data, response) {
        var result = JSON.parse(data);
        if (!result.success) {
            alert(result.msg);
            // 移除隊列中失敗項
        }
    }
});

完整鏈路保障

  1. 前端擴展名過濾:fileTypeExts 限制用戶選擇範圍
  2. 服務端文件頭驗證:ImageUtility.IsImage 核心攔截
  3. 保存時重命名:GUID + 正確擴展名,防止同名覆蓋與腳本執行
  4. 存儲目錄執行權限移除:IIS 設置上傳目錄無腳本執行權限

現代替代方案:HTML5 <input type="file" accept="image/*"> + File API 讀取 Blob 切片驗證文件頭,純前端即可完成首輪攔截,無需 Flash/Uploadify。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved