使用者選好檔案後就按下送出,結果上傳到一半才發現圖片太大——這種體驗很差。做法是先在選檔的 onchange 裡檢查格式與大小,不合規就直接擋下。
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- 用隱藏欄位帶入上限,方便後端動態調整 -->
<input type="hidden" name="MAX_FILE_SIZE" id="MAX_FILE_SIZE" value="8000000" />
<input type="file" name="files" id="files" onchange="checkFileType(this)" />
<script type="text/javascript">
var maxSize = document.getElementById('MAX_FILE_SIZE').value;
// 第一層:副檔名檢查
function checkFileType(obj) {
var path = obj.value.toString();
var perfix = path.substring(path.lastIndexOf('.') + 1);
var regExp = /^(jpg|jpeg|gif|png|bmp|webp)$/i;
if (perfix.match(regExp)) {
checkFileSize(obj);
} else {
alert('對不起,請選擇圖片檔案');
return false;
}
}
// 第二層:取得檔案大小,依瀏覽器能力降級
function checkFileSize(obj) {
var img = new Image();
try {
// 標準做法:直接讀 File 物件
return isLarged(obj.files.item(0).fileSize, maxSize);
} catch (e) {
try {
// 舊版 IE:靠 Image 物件的 fileSize
img.src = obj.value;
return isLarged(img.fileSize, maxSize);
} catch (e2) {
// 更舊的 IE:用選取範圍取路徑
obj.select();
var path = document.selection.createRange().text;
img.src = path;
return isLarged(img.fileSize, maxSize);
}
}
}
// 第三層:實際比對並提示
function isLarged(imgSize, maxSize) {
if (imgSize > maxSize) {
alert('對不起,您選擇的圖片檔案超過了 ' + parseInt(maxSize / 1024) + ' Kb');
return false;
} else {
alert(parseInt(imgSize / 1024) + ' kb,大小符合要求');
return true;
}
}
</script>
input.files[0].size 是現代瀏覽器的正解。副檔名可以隨便改。evil.jpg 實際上是執行檔也照样能通過 perfix.match()。真正的驗證必須在伺服器端做:檢查 MIME 型別、讀取檔案頭的 magic number、必要時重新編碼圖片。前端檢查只是為了「讓使用者早點知道」,不能當成安全措施。
input.addEventListener('change', function () {
var file = this.files[0];
if (!file) return;
var MAX = 8 * 1024 * 1024; // 8 MB
if (!/^image\/(jpeg|png|gif|webp|bmp)$/.test(file.type)) {
alert('請選擇圖片檔案');
this.value = '';
return;
}
if (file.size > MAX) {
alert('檔案不可超過 ' + (MAX / 1024 / 1024) + ' MB');
this.value = ''; // 清空,讓使用者能重選同一個檔
return;
}
console.log('檔案大小 ' + (file.size / 1024).toFixed(0) + ' KB,可以上傳');
});
8000000 約 7.6 MB,不是 8 MB。要剛好 8 MB 請寫 8 * 1024 * 1024。indexOf('.'),遇到 a.b.jpg 會取到 b.jpg 而誤判。aria-live 讓輔助技術能播報。change 不會觸發。createObjectURL(file) 搭配 Image.onload 讀 naturalWidth/naturalHeight,用完記得 revokeObjectURL。