JS 通過 input.files[0].type 判斷文件類型(image/text/audio/video/zip),桌面 Chrome 正常,手機瀏覽器無反應/報錯。
HTMLInputElement.files 屬於 File API,Android Chrome 40+ 支持,但:files 集合。function checkFile(input) {
const file = input.files?.[0] || input.value; // 兼容無 files 時取 value
const name = file.name || file; // file 可能是字符串路徑
const ext = name.substring(name.lastIndexOf('.') + 1).toLowerCase();
const allowed = ['jpg','jpeg','png','gif','bmp','txt','pdf','zip','rar','mp3','mp4'];
if (!allowed.includes(ext)) {
alert('不支持的文件類型');
input.value = ''; // 清空選擇
return false;
}
// 可選:文件大小校驗(需 File API 支持)
if (input.files?.[0]?.size > 500 * 1024 * 1024) { // 500MB
alert('文件過大');
input.value = '';
return false;
}
return true;
}
accept 屬性引導用戶選擇:<input type="file" accept="image/*,.pdf,.zip">