设置file input.value=null触发TypeError,如何正确清除文件输入?
前端文件上传大小限制报错修复方案
问题场景
要给内部网站控制台做前端快速修复:限制文件上传大小不超过29M,超出则清空文件输入框。当前代码功能能正常运行,但选择超大文件弹出提示并清空输入后,控制台会抛出Cannot read properties of undefined (reading 'size')的错误。
当前使用的代码:
HTML代码
<input id="myFile" class="form-control" type="file" name="attachment" placeholder="Attachment"/> </form> </body>
原JS代码
var myFile = document.getElementById('myFile'); myFile.addEventListener('change', function() { var maxSize = myFile.files[0].size; if (maxSize > 29000000) { alert("The attachment you've selected with a file size of " + maxSize + " bytes exceeds the maxium size permitted"); myFile.value = null; myFile.dispatchEvent(new Event('change')) } });
报错信息
test/:137 Uncaught TypeError: Cannot read properties of undefined (reading 'size') at HTMLInputElement.<anonymous> (test/:137:39) at HTMLInputElement.<anonymous> (test/:141:20)
报错原因
清空文件输入框时执行了myFile.value = null,紧接着手动触发了change事件。这时候文件输入框已经没有选中的文件,myFile.files是一个空的FileList,myFile.files[0]为undefined,读取它的size属性就会抛出类型错误。而且完全没必要手动触发change事件,清空操作本身不需要额外触发事件来通知。
修复后的代码
修改后的JS代码
var myFile = document.getElementById('myFile'); myFile.addEventListener('change', function() { // 先检查是否有选中文件,避免空指针错误 if (!myFile.files || myFile.files.length === 0) { return; } var fileSize = myFile.files[0].size; var maxAllowedSize = 29 * 1024 * 1024; // 用更易读的方式表示29M if (fileSize > maxAllowedSize) { alert("The attachment you've selected with a file size of " + fileSize + " bytes exceeds the maximum size permitted (29MB)"); myFile.value = null; // 清空文件输入框 } });
关键改动说明
- 增加空值检查:在读取文件大小前,先判断是否存在选中的文件,避免在无文件时执行后续代码导致报错。
- 移除不必要的
change事件触发:清空输入框后不需要手动触发change,既避免了报错,也符合浏览器默认行为。 - 优化大小写法:把
29000000改成29 * 1024 * 1024,代码可读性更强,也更准确(29MB实际是2910241024字节,和原数值接近但更规范)。
内容的提问来源于stack exchange,提问作者Gerald
相关产品推荐
相关产品推荐

