代码之家  ›  专栏  ›  技术社区  ›  Gerald

试图在addEventListener内设置表单的文件input.value=null

  •  1
  • Gerald  · 技术社区  · 1 年前

    我正在努力消除我的内部网站的网络控制台中的一些错误。此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)似乎也是导致错误的原因。我不是一个java脚本的人。检查表单元素的属性并使其无效的正确方法是什么?

    非常感谢。

    1 回复  |  直到 1 年前
        1
  •  1
  •   Hujaakbar    1 年前

    在您调度更改事件之后,错误发生在这里。 var maxSize = myFile.files[0].size;

    第一次,当有一个文件时,它工作正常。 但在你设定好之后 myFile.value null; , myFile.files 数组将变为空。但是,在调度更改事件后,您正试图访问它的第一个元素和第一个元素的大小, myFile.dispatchEvent(new Event('change')) .

    您可以删除发送更改事件的行 或 在访问数组元素之前,请检查数组是否包含元素:

    var myFile = document.getElementById('myFile');
        myFile.addEventListener('change', function() {
        if (myFile.files[0]){
            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'))
           }
            }
        });