Javascript 如何在上载所有输入类型之前附加事件以检查文件大小=";文件";?
我想在我网站上的所有输入type=“file”上附加一个事件,以检查文件大小是否高于5mo,如果是,则阻止上载并显示警告。有可能吗?您可以尝试以下方法: HTMLJavascript 如何在上载所有输入类型之前附加事件以检查文件大小=";文件";?,javascript,jquery,file-type,Javascript,Jquery,File Type,我想在我网站上的所有输入type=“file”上附加一个事件,以检查文件大小是否高于5mo,如果是,则阻止上载并显示警告。有可能吗?您可以尝试以下方法: HTML <input type="file" id="myFile" /> <span class="err"></span> 您可以只使用jQuery绑定更改事件: $('input[type="file"]').change(function(){ var f=this.files[0];
<input type="file" id="myFile" />
<span class="err"></span>
您可以只使用jQuery绑定更改事件:
$('input[type="file"]').change(function(){
var f=this.files[0];
var sizeInMb = f.size/1024;
var sizeLimit= 1024*5; // if you want 5 MB
if (sizeInMb > sizeLimit) {
alert('Sorry the file exceeds the maximum size of 5 MB!');
// reset the input (code for all browser)
this.replaceWith(input.val('').clone(true));
return false;
}
else {
// go on
}
}
希望这能有所帮助。可能是重复的谢谢!我对它做了一点修改,因为我的输入是通过使用$(document)动态生成的。在(“change”、“input[type=file]”、函数(event)上,它工作得很好
$('input[type="file"]').change(function(){
var f=this.files[0];
var sizeInMb = f.size/1024;
var sizeLimit= 1024*5; // if you want 5 MB
if (sizeInMb > sizeLimit) {
alert('Sorry the file exceeds the maximum size of 5 MB!');
// reset the input (code for all browser)
this.replaceWith(input.val('').clone(true));
return false;
}
else {
// go on
}
}