Skip to content
Advertisement

Applying javascript to check file size and extension

here is my script. What I am trying to do is to trigger it using onchange event. But it seems does not work very well. I have tried edit here and there but still facing problems. As for my latest edit below, the problem is, there is 2 files to be uploaded, but only the second one will display alert message, while the first one will just receive any file.

    <script>
    function checkFile()
    {   
    var node_list = document.getElementsByTagName('input');
    for (var i = 0; i < node_list.length; i++) 
    {
        var node = node_list[i];
        if (node.getAttribute('type') == 'file') 
        {
            var sFileName = node.value;
            var sFileExtension = sFileName.split('.')[sFileName.split('.').length - 1];
            var iFileSize = node.files[0].size;
            var iConvert=(node.files[0].size/10485760).toFixed(2);
        }


        if (sFileExtension != "pdf" && sFileExtension != "doc" && sFileExtension != "docx" && iFileSize>10485760)
        {   
            txt="File type : "+ sFileExtension+"nn";
            txt+="Size: " + iConvert + " MB nn";
            txt+="Please make sure your file is in pdf or doc format and less than 10 MB.nn";
            alert(txt);
        }
    }
}
    </script>

my form,

  <input type="file" name="file" id="confirm" onchange="checkFile()">
  <input type="file" name="file" id="approveletter" onchange="checkFile()">

Advertisement

Answer

Rather than relying on the elements them self you should use the given event to the function to get the file(s) that triggered the call to the callback function.

Passing in the event will guarantee you that you are actually working with the current files that caused the function to be called.

For example (I changed the variable name to make it more clear):

ONLINE DEMO HERE

/// pass in event 
function checkFile(e) {

    /// get list of files
    var file_list = e.target.files;

    /// go through the list of files
    for (var i = 0, file; file = file_list[i]; i++) {

        var sFileName = file.name;
        var sFileExtension = sFileName.split('.')[sFileName.split('.').length - 1].toLowerCase();
        var iFileSize = file.size;
        var iConvert = (file.size / 1048576).toFixed(2);

        /// OR together the accepted extensions and NOT it. Then OR the size cond.
        /// It's easier to see this way, but just a suggestion - no requirement.
        if (!(sFileExtension === "pdf" ||
              sFileExtension === "doc" ||
              sFileExtension === "docx") || iFileSize > 10485760) { /// 10 mb
            txt = "File type : " + sFileExtension + "nn";
            txt += "Size: " + iConvert + " MB nn";
            txt += "Please make sure your file is in pdf or doc format and less than 10 MB.nn";
            alert(txt);
        }
    }
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement