javascript Bootstrap 文件输入 - 限制文件类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33247452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 16:16:20  来源:igfitidea点击:

Bootstrap File Input - limit file types

javascriptjquery

提问by GRoston

Code that has been developed for a company that I am coaching uses Krajee's Bootstrap File Input. Where this function is called, allowedFileExtensions is set to allow only jpg, gif, and png. However, when the browse button is clicked, the list if allowed image file types shows about one dozen images types. If one that is not of the three types is selected, e.g., svg, the system shows an error message indicating that the file type is not allowed.

为我指导的公司开发的代码使用 Krajee 的 Bootstrap 文件输入。在调用此函数的地方,allowedFileExtensions 设置为仅允许 jpg、gif 和 png。但是,当单击浏览按钮时,如果允许的图像文件类型列表会显示大约一打图像类型。如果选择了不是这三种类型中的一种,例如svg,系统会显示错误消息,指示该文件类型不被允许。

While this certainly works, the browse should only allow the chosen types to be selected. What additional parameter(s) and/or other changes are needed so that the browse window limits the selection to the chosen types?

虽然这确实有效,但浏览应该只允许选择所选类型。需要哪些附加参数和/或其他更改,以便浏览窗口将选择限制为所选类型?

If it matters: I have seen this behavior on a PC with both Firefox and IE.

如果重要:我在装有 Firefox 和 IE 的 PC 上看到过这种行为。

回答by guest271314

While this certainly works, the browse should only allow the chosen types to be selected. What additional parameter(s) and/or other changes are needed so that the browse window limits the selection to the chosen types?

虽然这确实有效,但浏览应该只允许选择所选类型。需要哪些附加参数和/或其他更改,以便浏览窗口将选择限制为所选类型?

Try setting accepted types of file extension for input type="file"element using acceptattribute , with value being file extensions separated by comma . Only file extnsion types defined as value of acceptattribute should be displayed at "Open File" dialog

尝试input type="file"使用accept属性为元素设置可接受的文件扩展名类型,值是用逗号分隔的文件扩展名。只有定义为accept属性值的文件扩展类型才应显示在“打开文件”对话框中

<input type="file" accept=".jpg,.gif,.png" />

回答by Joseph Norris

Here is what I used.

这是我使用的。

//update file name text box with selected filepath and file
$('#FileUpload1').change(function ()
{
    var filename = $(this).val();

    $('#txtFileName').val(filename);

    var fileExtension = ['xlsx', 'xls', 'csv'];
    if ($.inArray(filename.split('.').pop().toLowerCase(), fileExtension) == -1)
    {
        $('#lblWarning').show();
        $('#lblWarning').text("Only 'xlsx', 'xls', 'csv' formats are allowed.");
    }
    else
    {
        $('#lblWarning').hide();
    }


});