Bootstrap 4 / jQuery - 清除输入框中的文件名 <input type='file' /> bs-custom-file-input

6

我有一个使用了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,但我无法使它工作起来。


你能否使用JavaScript来移除输入框,然后再替换它? - mega12345mega
不确定如何做到这一点,你能在 Fiddle 中尝试吗? - Matt
3个回答

6

没有需要清除的值,该插件为自定义文件(custom-file)生成一个标签(label),你看到的不是输入框而是标签。如果你使用浏览器检查工具,你可以看到它。将这个:

// Clear the value
$('#customFile').val('');

根据这个:

// Clear the value, replace it by whatever text you want
$('#customFile').next('label').html('Select a file');

似乎不起作用(仅在选择大于1MB的文件时出现)。当我首先选择小于1MB的文件并更改为大于1MB的文件时,标签不会更改。我已更新了fiddle:https://jsfiddle.net/Matti79/racv6w4d/23,因此您也可以自己尝试。 - Matt
它不起作用是因为您在更改时重新初始化了bs-custom-file,您只需要初始化一次即可。只需取出bsCustomFileInput.init();并将其放置在$(document).ready之后即可。 - webolive
1
成功了。谢谢webolive!更新了Fiddle以提供一个可用的示例。 - Matt

5

这适用于单个字段。它支持具有子标签的标签(用于长名称或多个文件)。

function remove_selected(id_input){
   var fileInput = document.getElementById(id_input)
   fileInput.value = ''
   fileInput.dispatchEvent(new Event('change'));
}

remove_selected('file');

来源:https://github.com/Johann-S/bs-custom-file-input/issues/86

这个问题是因为在Firefox浏览器中,当你选择一个文件时,它会自动提交表单。为了避免这种情况,可以将 "type" 属性设置为 "button"。这个问题已经在 bs-custom-file-input v1.3.4 中得到修复。


1
唯一对我有效的解决方案,Vanilla万岁 :) - Jonas WebDev
如果您能添加为什么这个方法有效的原因,那就太好了。原因是:bs-custom-fileinput订阅了输入框的“change”事件,但当您以编程方式更改值时,此事件不会被触发。因此,我们只能手动触发它。这就是JS的工作方式;与Winforms/WPF/WinUI中的C#不同。 - Daniel Wu
它运行得很好,但我想转换为像trigger("change")这样的jq格式,但失败了,有人知道为什么吗? - Bater Chen

0

尝试复制 HTML 代码:

// At beginning
var div = $('.custom-file')[0]; // Or use an ID
var html = div.innerHTML;

// To clear the input
div.innerHTML = html;

它只是记住了空输入字段的样子,并相应地更新代码。

请记住,div内的所有内容都会被重置。为了防止这种情况,请在输入框周围添加一个额外的容器:

<div class="custom-file">
    <span id="customFileInputContainer">
        <input type="file" class="custom-file-input" id="customFile">
    </span>
    <label class="custom-file-label" for="customFile" data-browse="Browse">Select a file</label>
</div>

JavaScript需要进行更改以适应此变化:

var div = $('#customFileInputContainer')[0];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接