HTML <input type='file'> 应用过滤器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3521122/
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-08-29 04:11:57  来源:igfitidea点击:

HTML <input type='file'> apply a filter

htmlformsfilefilter

提问by Moon

<input type='file' name='userFile'>

now when i will click the browse button, the browse dialog will show all files... what if i want to filter file types lets say

现在当我单击浏览按钮时,浏览对话框将显示所有文件...如果我想过滤文件类型怎么办?

  • only images or .png& .jpg& .gifs
  • only office file like .doc& .docx& .pps
  • 仅图像或.png& .jpg& .gifs
  • 只有像.doc& .docx& .pps这样的办公文件

how to do it...

怎么做...

采纳答案by cHao

There is an "accept" attribute on file input controls, where you can specify the types of files you want. From what i'm seeing, though, many browsers like to ignore it -- the file types that can be specified are MIME types, so a strictly correct browser would have to look at every file regardless of extension and see if it's an image (and if so, what type it is).

文件输入控件有一个“accept”属性,您可以在其中指定所需的文件类型。 但是,从我所看到的,许多浏览器喜欢忽略它——可以指定的文件类型是 MIME 类型,所以一个严格正确的浏览器必须查看每个文件,而不管扩展名如何,看看它是否是一个图像(如果是这样,它是什么类型)。

Update:It seems at least some version of every major browser on Windows now provides at least some support for the acceptattribute. (Even IE supports it, as of version 10.) However, it's still a bit early yet to rely on it, as IE 8 and 9 still don't support it. And support in general is a bit spotty.

更新:似乎 Windows 上每个主要浏览器的至少某个版本现在至少为该accept属性提供了一些支持。(即使 IE 支持它,从版本 10 开始。)但是,现在依赖它还为时过早,因为 IE 8 和 9 仍然不支持它。总体而言,支持有点参差不齐。

  • Chrome seems to have full support. It uses its own built-in list of types as well as the system's...so if either one defines the type, Chrome knows which files to show.
  • IE 10 supports file extensions beautifully, and MIME types decently. It seems to use only the system's mapping of MIME type to extensions, though...which basically means if something on the user's computer didn't register those extensions with the right MIME types, IE won't show files of those MIME types.
  • Opera only seems to support MIME types -- to the point where extensions actually disable the filter -- and the UI for the file selector sucks. You have to select a type in order to see the files of that type.
  • Firefox appears to support only a limited set of types, and ignore other types as well as extensions.
  • I don't have Safari, and don't plan on downloading it. If someone could document Safari's support...Partial support on safari. http://caniuse.com/#search=accept
  • Chrome 似乎完全支持。它使用自己的内置类型列表以及系统的......所以如果其中任何一个定义了类型,Chrome 就会知道要显示哪些文件。
  • IE 10 很好地支持文件扩展名,并且很好地支持 MIME 类型。它似乎只使用系统将 MIME 类型映射到扩展名,不过……这基本上意味着如果用户计算机上的某些内容没有使用正确的 MIME 类型注册这些扩展名,IE 将不会显示这些 MIME 类型的文件。
  • Opera 似乎只支持 MIME 类型——以至于扩展实际上禁用了过滤器——而且文件选择器的 UI 很糟糕。您必须选择一种类型才能查看该类型的文件。
  • Firefox 似乎只支持有限的一组类型,而忽略其他类型和扩展。
  • 我没有 Safari,也不打算下载它。如果有人可以记录 Safari 的支持...对 safari 的部分支持。http://caniuse.com/#search=accept

You should consider adding the attribute, so browsers that support it can help the user find the right files more easily. But i would still suggest that you check the filename after the file's selected and show an error message if a file with the wrong extension is uploaded.

您应该考虑添加该属性,以便支持它的浏览器可以帮助用户更轻松地找到正确的文件。但我仍然建议您在选择文件后检查文件名,如果上传了错误扩展名的文件,则显示错误消息。

And of course, definitely have the server double-check that the file is the right type. File extensions are just a naming convention, and can be easily subverted. And even if we could trust the browser (which we can't), and even if it did attempt to filter stuff as you asked (which it might not), the chance of it actually verifying that that .docfile is truly a Word document is next to nil.

当然,一定要让服务器仔细检查文件的类型是否正确。文件扩展名只是一种命名约定,很容易被颠覆。即使我们可以信任浏览器(我们不能),即使它确实尝试按照您的要求过滤内容(它可能不会),它实际验证该.doc文件确实是 Word 文档的机会是在零旁边。

回答by ravi404

I think u are looking for the accept parameter. Try this works

我想你正在寻找接受参数。试试这个作品

<input type="file" accept="image/*" />

回答by JMnerd

It should use MIME_type: For example

它应该使用MIME_type:例如

<input type="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" />

this will only accept *.xlsxfile type...

这将只接受*.xlsx文件类型...

For the list of mime types, check the link below:
http://www.bitsandpix.com/entry/microsoft-office-2007-2010-docx-xlsx-pptx-mime-type-to-avoid-the-zip-issue/

有关 mime 类型列表,请查看以下链接:http:
//www.bitsandpix.com/entry/microsoft-office-2007-2010-docx-xlsx-pptx-mime-type-to-avoid-the-zip-问题/

回答by stevemegson

You can't control which files can be selected, but you can read the filename with javascript after the file is chosen. You could then display a warning and/or disable the submit button if the file is the wrong type. However, remember that you can't rely on the extension to tell you whether or not the file is really of the right type. It should only be treated as a way to help users who might otherwise waste time uploading a huge file before discovering that you don't support that file type.

您无法控制可以选择哪些文件,但您可以在选择文件后使用 javascript 读取文件名。如果文件类型错误,您可以显示警告和/或禁用提交按钮。但是,请记住,您不能依靠扩展名来告诉您文件是否真的是正确的类型。它应该只被视为一种帮助用户的一种方式,否则他们可能会在发现您不支持该文件类型之前浪费时间上传一个巨大的文件。

Here's some example code to do that. It uses jQuery, but you could do the same in plain javascript too.

这是一些示例代码来做到这一点。它使用 jQuery,但你也可以用普通的 javascript 做同样的事情。

$(function() {
    $('#inputId').change( function() {
        var filename = $(this).val();
        if ( ! /\.txt$/.test(filename)) {
            alert('Please select a text file');
        }
    });
});

回答by lmiguelmh

You could use JavaScript. Take in consideration that the big problem with doing this with JavaScript is to reset the input file. Well, this restricts to only JPG (for other formats you will have to change the mime typeand the magic number):

你可以使用 JavaScript。考虑到使用 JavaScript 执行此操作的大问题是重置输入文件。好吧,这仅限于 JPG(对于其他格式,您必须更改mime 类型幻数):

<form id="form-id">
  <input type="file" id="input-id" accept="image/jpeg"/>
</form>

<script type="text/javascript">
    $(function(){
        $("#input-id").on('change', function(event) {
            var file = event.target.files[0];
            if(file.size>=2*1024*1024) {
                alert("JPG images of maximum 2MB");
                $("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
                return;
            }

            if(!file.type.match('image/jp.*')) {
                alert("only JPG images");
                $("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
                return;
            }

            var fileReader = new FileReader();
            fileReader.onload = function(e) {
                var int32View = new Uint8Array(e.target.result);
                //verify the magic number
                // for JPG is 0xFF 0xD8 0xFF 0xE0 (see https://en.wikipedia.org/wiki/List_of_file_signatures)
                if(int32View.length>4 && int32View[0]==0xFF && int32View[1]==0xD8 && int32View[2]==0xFF && int32View[3]==0xE0) {
                    alert("ok!");
                } else {
                    alert("only valid JPG images");
                    $("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
                    return;
                }
            };
            fileReader.readAsArrayBuffer(file);
        });
    });
</script>

Take in consideration that this was tested on latest versions of Firefox and Chrome, and on IExplore 10.

考虑到这是在最新版本的 Firefox 和 Chrome 以及 IExplore 10 上测试过的。

For a complete list of mime types see Wikipedia.

有关 mime 类型的完整列表,请参阅 Wikipedia

For a complete list of magic number see Wikipedia.

有关幻数的完整列表,请参阅维基百科

回答by Brett Weber

I have made an easy way for client side validation for most cases on file filtering. It is actually quite simple. Now, before you go and try to implement this, understand that the server MUST check this file, because the javascript and HTML filtering is not a sure thing in cases where someone alters the .js, or even the HTML. I'm not including all of the actual script for the simple fact that I enjoy seeing other implement the concepts using a creative mind, but these are the steps I've taken that seem to work until I find a better answer:

对于文件过滤的大多数情况,我已经为客户端验证制定了一种简单的方法。其实很简单。现在,在你去尝试实现这个之前,要明白服务器必须检查这个文件,因为在有人改变 .js 甚至 HTML 的情况下,javascript 和 HTML 过滤是不确定的。我不包括所有实际脚本,因为我喜欢看到其他使用创造性思维实现概念的简单事实,但这些是我已经采取的步骤,在我找到更好的答案之前,这些步骤似乎有效:

Create a js object that finds the input and handles it.

创建一个 js 对象来查找输入并处理它。

Call a function, such as the OnClientUploadComplete for the AjaxControlToolKit's AsyncFileUpload control.

调用一个函数,例如 AjaxControlToolKit 的 AsyncFileUpload 控件的 OnClientUploadComplete。

Inside of this function, declare a boolean variable: bIsAccepted(set to false) and string sFileName(after getting the filename from the args).

在此函数内部,声明一个布尔变量:bIsAccepted(设置为 false)和字符串 sFileName(从 args 获取文件名后)。

In an if..else Statement,

在 if..else 语句中,

if(sFilename.indexOf(".(acceptedExtension1)") ||
   sFileName.indexOf(".(AcceptedExtension2)") )
{
   bIsAccepted = true;
}
else
{
   bIsAccepted = false;
}

then

然后

if(bIsAccepted)
{
//Process Data
}

On the server, setting up a list of accepted file extensions and looping through and processing similarly will make the process cohesive and consistent, effectively allowing the UI and Code-Behind to filter the file types in almost every situation.

在服务器上,设置一个可接受的文件扩展名列表并进行类似的循环和处理将使流程具有凝聚力和一致性,从而有效地允许 UI 和代码隐藏在几乎所有情况下过滤文件类型。

Given that this can be bypassed by changing the name to have a different file extension as part of the name, the mime type should also be checked before submitting to the server for further processing.

鉴于可以通过将名称更改为具有不同的文件扩展名作为名称的一部分来绕过这一点,因此在提交给服务器进行进一步处理之前,还应检查 mime 类型。

            [http://www.webmaster-toolkit.com/mime-types.shtml][1]

Hope this helps!

希望这可以帮助!

回答by fantactuka

You should use one of the pluginsthat use embeded Flash, since you can't do it with plain javascript

您应该使用使用嵌入式 Flash的插件之一,因为您无法使用普通的 javascript

回答by Soham

Using MVC we can restrict upload to zip files only

使用 MVC 我们可以限制上传到 zip 文件

.HtmlAttributes(new { accept = ".zip*" })