必须用JavaScript校验file input的格式与大小:通过change事件获取File对象,用name取后缀比对白名单,用size比对字节数阈值,不通过则清空input并提示。

在 file input 中限制文件格式与大小,不能仅靠 HTML 属性(如 accept 或 maxlength)实现真正可靠的校验——accept 只影响文件选择器的界面过滤,用户仍可绕过;maxlength 对 file input 无效。必须结合 JavaScript 的 change 事件 + 文件对象属性进行实时校验。
监听 change 事件并读取选中文件
file input 的值变化时触发 change,此时可通过 files[0] 获取首个选中文件(多选则遍历 files 类数组)。
注意:files 是只读的 FileList,每个项是 File 对象(继承自 Blob),具备 name、size、type 等属性。
按文件后缀(扩展名)限制格式
File.name 包含完整文件名,可用字符串方法提取后缀并比对白名单。相比 File.type(MIME 类型),后缀更可控、不易被伪造(但仍是前端校验,服务端必须二次验证)。
立即学习“Java免费学习笔记(深入)”;
- 用
filename.split('.').pop().toLowerCase()获取小写后缀 - 定义允许的后缀数组,如
['jpg', 'jpeg', 'png', 'gif'] - 检查
ext.includes(allowedExtensions),不通过则清空 input 并提示
按文件字节数限制大小
File.size 单位为字节(bytes),直接比较数值即可。常见限制如 2MB = 2 * 1024 * 1024 = 2097152 字节。
- 获取
file.size,与最大允许字节数对比 - 超限时调用
input.value = ''清空已选文件(这是重置 input 的标准方式) - 建议同时提示具体限制值(如“文件不能超过 2MB”),提升体验
完整示例代码(含错误反馈)
将校验逻辑封装为函数,在 change 事件中调用:
<input type="file" id="avatar" accept="image/*">
<div id="error" style="color:red;font-size:14px;"></div>
<p><script>
const input = document.getElementById('avatar');
const errorEl = document.getElementById('error');
const allowedExts = ['jpg', 'jpeg', 'png', 'gif'];
const maxSize = 2 <em> 1024 </em> 1024; // 2MB</p><p>input.addEventListener('change', () => {
errorEl.textContent = '';
const file = input.files[0];
if (!file) return;</p><p>// 检查后缀
const ext = file.name.split('.').pop().toLowerCase();
if (!allowedExts.includes(ext)) {
errorEl.textContent = <code>仅支持 ${allowedExts.join(',')} 格式</code>;
input.value = ''; // 清空选择
return;
}</p><p>// 检查大小
if (file.size > maxSize) {
errorEl.textContent = <code>文件不能超过 ${maxSize / 1024 / 1024}MB</code>;
input.value = '';
}
});
</script>


















