简体   繁体   English

使用javascript添加更多按钮功能来验证上传文件的大小

[英]Validate upload file size with add more button functionality using javascript

I have following html code for upload file 我有以下用于上传文件的html代码

<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 和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. 现在,我要验证每个文件大小,最大大小为3 MB,在客户端上载。

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. StackOverflow是一个很好的指南库。

Look this question, It has answered very well: 看这个问题,它回答得很好:

JavaScript file upload size validation JavaScript文件上传大小验证

You can adapt your code to make this validation. 您可以修改您的代码以进行此验证。

Simple Example: 简单的例子:

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

HTML: HTML:
 <div id="myFiles"> <input type="file"> </div> <button id="btnAdd">Add</button> 
Javascript: 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. 干杯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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