gpt4 book ai didi

javascript - 使用动态创建的文件输入字段进行 Jquery 文件验证

转载 作者:行者123 更新时间:2023-11-28 06:32:28 24 4
gpt4 key购买 nike

我想验证文件输入字段,例如大小扩展名

我根据客户要求附加更多文件输入字段。看截图

https://drive.google.com/file/d/0B7DnAEDiJntwY0pkeXlya0xPdzg/view?usp=sharing

当我使用以下函数检查文件名和大小时。但它不适用于动态创建的元素。

 <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);
});

当用户单击加号按钮时,将生成并操作新的上传字段。

如何在 jquery 中获取文件名和大小?

谢谢

最佳答案

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]

试试这个:

$(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>

Fiddle here

关于javascript - 使用动态创建的文件输入字段进行 Jquery 文件验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34584659/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com