我有一个使用了Bootstrap的表单,其中涉及到一个推荐插件bs-custom-file-input
来进行自定义文件上传的动画效果。详见:https://getbootstrap.com/docs/4.5/components/forms/#file-browser
该表单包含一个字段以添加附件。
如果用户选择的文件大小超过1MB,则会显示一个带有错误消息的警告框。
如何在错误消息后清除输入字段中的文件名?
以下是我的代码:
HTML表单
<div class="container">
<div class="row">
<div class="col-md-12">
<form id="testform" method="post" enctype="multipart/form-data">
<div class="form-row">
<div class="form-group col-12">
<label for="customFile">Attachment</label>
<div class="custom-file">
<input type="file" class="custom-file-input" id="customFile">
<label class="custom-file-label" for="customFile" data-browse="Browse">Select a file</label>
</div>
</div>
</div>
</form>
</div>
</div>
$(document).ready(function() {
$('#customFile').on('change', function() {
// The recommended plugin to animate custom file input: bs-custom-file-input, is what bootstrap using currently
bsCustomFileInput.init();
// Set maximum filesize
var maxSizeMb = 1;
// Get the file by using JQuery's selector
var file = $('#customFile')[0].files[0];
// Make sure that a file has been selected before attempting to get its size.
if(file !== undefined) {
// Get the filesize
var totalSize = file.size;
// Convert bytes into MB
var totalSizeMb = totalSize / Math.pow(1024,2);
// Check to see if it is too large.
if(totalSizeMb > maxSizeMb) {
// Create an error message
var errorMsg = 'File too large. Maximum file size is ' + maxSizeMb + ' MB. Selected file is ' + totalSizeMb.toFixed(2) + ' MB';
// Show the error
alert(errorMsg);
// Clear the value
$('#customFile').val('');
// How to clear the filename in the input field?
alert('How to clear the filename in the input field?');
// Return FALSE
return false;
}
}
});
});
编辑:可运行的Fiddle如下: https://jsfiddle.net/Matti79/racv6w4d/15/
我在这里发现了一个问题:https://github.com/Johann-S/bs-custom-file-input/issues/37,但我无法使它工作起来。