简体   繁体   中英

Not able to validate file size for multi file upload in javascript

I have file upload action in an html page and I am able to validate for file size for single file upload using the below javascript. How can I validate for multi file upload.

<input type="file" id="fileUpload" />
<input type="button" id="upload" value="Upload" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
    $("#upload").bind("click", function () {
        if (typeof ($("#fileUpload")[0].files) != "undefined") {
            var size = parseFloat($("#fileUpload")[0].files[0].size / (1024*1024)).toFixed(2);
            if(size < 5.00){
                alert("You are eligible to upload file");
            }
            else{
                alert("This File is too large");
            }
        } else {
            alert("This browser does not support HTML5.");
        }
    });
});
</script>

Here below I have input field for multi file upload

<input type="file" id="fileUpload" name="upload[]" multiple="multiple"/>
<input type="button"  id="upload" value="Upload"/>

Use each loop to get each file one by one and the validate the size as you are doing right now for first file.

<script type="text/javascript">
$(function () {
    $("#upload").bind("click", function () {
        if (typeof ($("#fileUpload")[0].files) != "undefined") {
            var files = $("#fileUpload")[0].files;
            $.each(files, function (index,file) {
                var size = parseFloat(file.size / (1024 * 1024)).toFixed(2);
                if (size < 5.00) {
                    alert("You are eligible to upload file");
                }
                else {
                    alert("This File is too large");
                }
            });
        } else {
            alert("This browser does not support HTML5.");
        }
    });
});
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM