上一篇實現了服務端驗證,但用戶上傳非圖片時仍需等待上傳完成才收到錯誤,體驗差。需在客戶端選擇文件瞬間攔截非圖片,取消上傳並提示。
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);
}
}
[HttpPost]
public ActionResult Upload(HttpPostedFileBase fileData) {
if (!ImageUtility.IsImage(fileData)) {
return Json(new { success = false, msg = "請選擇圖片文件" });
}
// 保存邏輯...
return Json(new { success = true, path = savedPath });
}
$('#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);
// 移除隊列中失敗項
}
}
});
fileTypeExts 限制用戶選擇範圍ImageUtility.IsImage 核心攔截現代替代方案:HTML5
<input type="file" accept="image/*">+ File API 讀取 Blob 切片驗證文件頭,純前端即可完成首輪攔截,無需 Flash/Uploadify。