封裝為 UpLoadFileCheck 類別,支援驗證副檔名、檔案大小、圖片寬高,相容 IE 專屬 fileSize 屬性與標準 Image 物件載入檢測,提供完整錯誤訊息回呼。
function UpLoadFileCheck() {
this.AllowExt = '.jpg,.gif'; // 允許副檔名,0 為不限制
this.AllowImgFileSize = 0; // 允許大小(KB),0 不限制
this.AllowImgWidth = 0; // 允許寬度(px),0 不限制
this.AllowImgHeight = 0; // 允許高度(px),0 不限制
this.ImgObj = new Image();
this.ErrMsg = '';
this.IsImg = false; // 是否啟用圖片屬性檢測
}
CheckExt 取得 input.value 截取副檔名,對照 AllowExt 白名單。CheckProperty 將 input.value 指派給 Image.src,利用 readyState === 'complete'(IE)或 onload 事件等待載入完成,讀取 width/height/fileSize 進行比對。ErrMsg,最終透過 ShowMsg(預設 alert)回報。<input type="file" onchange="validate(this)" />
<script>
function validate(obj) {
var checker = new UpLoadFileCheck();
checker.IsImg = true;
checker.AllowImgFileSize = 100; // 限制 100KB
checker.AllowExt = '.jpg,.png,.gif';
checker.CheckExt(obj);
}
</script>
input.addEventListener('change', async (e) => {
const file = e.target.files[0];
if (!file) return;
// 檔案大小
if (file.size > 100 * 1024) return alert('超過 100KB');
// 檔案類型
if (!['image/jpeg', 'image/png', 'image/gif'].includes(file.type)) return alert('格式不支援');
// 圖片尺寸
const img = new Image();
img.src = URL.createObjectURL(file);
await new Promise(r => img.onload = r);
if (img.width > 800 || img.height > 600) return alert('尺寸超過限制');
URL.revokeObjectURL(img.src);
// 通過驗證,可送出表單或上傳
});
使用 File API + Object URL 免去舊版 IE 相容包袱,程式碼更簡潔、非同步流程更清晰。