I want to Validate File input field like size and extension .
I am appending more file input field based on the client requirment. See the screenshot
https://drive.google.com/file/d/0B7DnAEDiJntwY0pkeXlya0xPdzg/view?usp=sharing
When I use the below function to check the file name and size. but it not working on dynamically created elements.
<span class="input-group-addon btn btn-Choose btn-file">
<span class="fileinput-new">Browse File</span>
<span class="fileinput-exists">Change</span>
<input class="fileimgval" type="file" name="brchrimg[]">
</span>
$(document).on('change','input:file',function(){
var fileName = $(this).val();
alert(fileName);
});
When User click on the Plus button a new upload field in generating and manipulating with that.
How can I get the filename and size in jquery ?
Thanks
HTML 5 File API specification, some properties of files are accessible at client side and file size is one of them. So the idea is to use the size property and find out the file size. But as it is a part of HTML 5 specification so it will only work for modern browsers. [Ref]
Try this:
$(document).on('change', 'input:file', function() { var fileName = $(this).val(); var iSize = $(this)[0].files[0].size / 1024; var size = ''; if (iSize / 1024 > 1) { if (((iSize / 1024) / 1024) > 1) { iSize = (Math.round(((iSize / 1024) / 1024) * 100) / 100); size = iSize + "Gb"; } else { iSize = (Math.round((iSize / 1024) * 100) / 100); size = iSize + "Mb"; } } else { iSize = (Math.round(iSize * 100) / 100); size = iSize + "kb"; } alert('fileName: ' + fileName + ' size: ' + size); }); $('#addMore').on('click', function() { var html = '<br><span class="input-group-addon btn btn-Choose btn-file">\\ <span class="fileinput-new">Browse File</span>\\ <span class="fileinput-exists">Change</span>\\ <input class="fileimgval" type="file" name="brchrimg[]">\\ </span>'; $('#parent').append(html); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <div id='parent'> <span class="input-group-addon btn btn-Choose btn-file"> <span class="fileinput-new">Browse File</span> <span class="fileinput-exists">Change</span> <input class="fileimgval" type="file" name="brchrimg[]"> </span> </div> <Button id='addMore'>Add More</Button>
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.