Search code examples
javascriptaddeventlistener

Trying to set a form's file input.value = null inside addEventListener


I'm trying to get rid of some errors in the web console of my internal site. This JS is not meant to serve as proper form validation or be security minded, it's only done to apply a quick fix on the frontend of a completely internal site to limit the upload size and clear the form's file input if the size exceeds 29M. I'm just curious of how to clear the input without having these errors.

...
                <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'))
        }
    });
...

In the java console, when a file is selected on input id="myFile" which is > 29000000 bytes, I get the alert, and the following on the console:

test/:137 Uncaught TypeError: Cannot read properties of undefined (reading 'size')
    at HTMLInputElement.<anonymous> (test/:137:39)
    at HTMLInputElement.<anonymous> (test/:141:20)

Everything technically "works" but it would appear that even though the condition to check for file size is an "if" and not a "while", clearing the value inside the if block (myFile.value = null) seems to be the cause of the error. I am NOT a java-script person. What's the correct way to check for properties on a form element and nullify that same element?

Thank you!


Solution

  • The error is happening here, after you dispatch change event. var maxSize = myFile.files[0].size;

    In the first time, when there is a file, it is working correctly. But after you set myFile.value to null;, myFile.files array will become empty. However, you are trying to access its first element and the size of the first element after you dispatch change event, myFile.dispatchEvent(new Event('change')).

    You can either remove the line that dispatches the change event or Before accessing array elements, check array contains elements:

    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'))
           }
            }
        });