简体   繁体   中英

Validate upload file size with add more button functionality using javascript

I have following html code for upload file

<div class="form-group">
    <label class="col-sm-2 control-label" for="inputPassword3">Attach Files: </label>
    <div class="col-sm-10">
        <div id="filediv">
            <input name="file[]" type="file" id="file" />
        </div>
        <input type="button" id="add_more" class="upload" value="Add More 
    Files" />
    </div>
</div>

And js

$('#add_more').click(function () {
    $(this).before($("<div/>", {
        id: 'filediv'
    }).fadeIn('slow').append($("<input/>", {
        name: 'file[]',
        type: 'file',
        id: 'file'
    }), $("<br/>")));
});

Now I want to validate each file Size which is max 3 MB uploaded on client side.

A good practice is searching before making a question here because there are a lot of awesome answers. StackOverflow is a great repository of guidance.

Look this question, It has answered very well:

JavaScript file upload size validation

You can adapt your code to make this validation.

Simple Example:

https://jsfiddle.net/klassmann/3puwba2v/2/

HTML:
 <div id="myFiles"> <input type="file"> </div> <button id="btnAdd">Add</button> 
Javascript:
 function fileValidation(e){ console.log(); var filelist = $(this).get(0).files; var firstfile = filelist[0]; var filesize = (firstfile.size / 1024) / 1024; if (filesize > 3.0) { alert('File has more than 3MB'); } else { alert('File is valid.'); } } $("input[type=file]").on('change',fileValidation); $("#btnAdd").on('click', function(){ var $newFile = $("<input type='file'>"); $newFile.on('change', fileValidation); $("#myFiles").append($newFile); }); 

Cheers.

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