我正在尝试消除内部网站的网络控制台中的一些错误。该 JS 并不是为了充当适当的表单验证或安全意识,它只是为了在完全内部站点的前端应用快速修复以限制上传大小并在大小超过 29M 时清除表单的文件输入。我只是好奇如何清除输入而不出现这些错误。
...
<input id="myFile" class="form-control" type="file" name="attachment" placeholder="Attachment"/>
</form>
</body>
...
...
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'))
}
});
...
在java控制台中,当在输入id =“myFile”上选择> 29000000字节的文件时,我收到警报,并在控制台上显示以下内容:
test/:137 Uncaught TypeError: Cannot read properties of undefined (reading 'size')
at HTMLInputElement.<anonymous> (test/:137:39)
at HTMLInputElement.<anonymous> (test/:141:20)
从技术上讲,一切都“有效”,但看起来即使检查文件大小的条件是“if”而不是“while”,清除 if 块内的值 (myFile.value = null) 似乎是原因的错误。我不是一个 JavaScript 人。检查表单元素上的属性并取消同一元素的正确方法是什么?
谢谢你!