[英]File upload form, attach a file condition
I have a file upload form with jquery validator to check a file size. 我有一个带有jquery验证程序的文件上传表单,用于检查文件大小。 Validator fires, I have a proper IF statement, but how to prevent a file from being attached?
验证程序触发,我有正确的IF语句,但是如何防止文件被附加? I thought return would do the trick, but a file is 'attached' to the upload button anyways (a file name appears next to it).
我以为return可以解决问题,但是无论如何文件都会“附加”到上传按钮上(文件名会显示在文件旁边)。
$('#fileUploadButton').on('change', function() {
var fileSizeInBytes = this.files[0].size;
if(fileSizeInBytes>512000){
alert("this file is to big!");
return;
}else{
//generate preview
}
});
Please check below mentioned solution. 请检查以下提到的解决方案。
$('#fileUploadButton').on('change', function() {
var fileSizeInBytes = this.files[0].size;
if(fileSizeInBytes>512000){
alert("this file is to big!");
// Reset file input
$('input[type="file"]').val('');
// OR
$('#input_file_id').val('');
return;
}else{
//generate preview
}
});
Use $(this).val('');
使用
$(this).val('');
or this.value = ''
. 或
this.value = ''
。 It will clear the selected value for file input. 它将清除所选值以进行文件输入。
$('#fileUploadButton').on('change', function(e) { var fileSizeInBytes = this.files[0].size; if(fileSizeInBytes>100){ alert("this file is to big!"); $(this).val(''); //or this.value = ''; return; }else{ //generate preview } });
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script> <input type="file" id="fileUploadButton" />
Change file size as per requirement. 根据要求更改文件大小。 I have added 100 for testing.
我添加了100个进行测试。
Just clear the file input's value: 只需清除文件输入的值即可:
$('#fileUploadButton').on('change', function() {
var fileSizeInBytes = this.files[0].size;
if (fileSizeInBytes > 512000){
alert("this file is to big!");
$(this).val('');
return;
} else {
//generate preview
}
}); });
And a bit of pure js way to do this: 和一些纯js的方式来做到这一点:
$('#fileUploadButton').on('change', function() {
var fileSizeInBytes = this.files[0].size;
if(fileSizeInBytes>512000){
alert("this file is to big!");
//pure js input reset
document.getElementById(this.id).value = '';
return;
}else{
//generate preview
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.