0

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.

George
  • 6,630
  • 2
  • 29
  • 36
Sanj
  • 141
  • 1
  • 8

1 Answers1

0

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.

klassmann
  • 518
  • 10
  • 14
  • @kiassmann all codes work for only first file upload,but when i click on add more button and after that new file browse appear and for that input validation is not working. – Sanj Oct 17 '17 at 12:56
  • On add more button dynamically input filled created and same id will generated for each input field. Some one help me to solve this issue. – Sanj Oct 17 '17 at 13:14