Html 将文件上传选择限制为特定类型

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

restrict file upload selection to specific types

htmlfile-uploadfileapi

提问by ndmweb

Anyway to restrict the selection of file types via the <input type="file" />element?

无论如何要通过<input type="file" />元素限制文件类型的选择?

For instance, if I wanted only images types to be uploaded, I would restrict the possible selections to (image/jpg,image/gif,image/png), and the selection dialog would grey out files of other mime types.

例如,如果我只想上传图像类型,我会将可能的选择限制为 (image/jpg,image/gif,image/png),并且选择对话框会使其他 mime 类型的文件变灰。

p.s. I know that I can do this after the fact with the File API by scanning the .type attributes. I'm really trying to restrict this before hand.. I also know I can do this via flash, but I do NOT want to have use flash for this.

ps 我知道我可以通过扫描 .type 属性来使用 File API 做到这一点。我真的想事先限制这个。我也知道我可以通过闪光灯来做到这一点,但我不想为此使用闪光灯。

回答by amosrivera

There is an html attribute for this specific purpose called acceptbut it has little support across browsers. Because of this server side validation is recommended instead.

有一个用于此特定目的的 html 属性,accept但它几乎不受浏览器的支持。因此,建议改为使用服务器端验证。

<input type="file" name="pic" id="pic" accept="image/gif, image/jpeg" />

If you don't have access to the backend have a look at a flash based solution like SWFUpload.

如果您无权访问后端,请查看基于 Flash 的解决方案,例如SWFUpload

See more on this here: File input 'accept' attribute - is it useful?

在此处查看更多信息:文件输入“接受”属性 - 有用吗?

回答by Radek Pech

It's better to let user select any file, and then check its type - this is better supported by the browsers:

最好让用户选择任何文件,然后检查其类型 - 浏览器更好地支持:

var
    file = (el[0].files ? el[0].files[0] : el[0].value || undefined),
    supportedFormats = ['image/jpg','image/gif','image/png'];

if (file && file.type) {
    if (0 > supportedFormats.indexOf(file.type)) {
        alert('unsupported format');
    }
    else {
        upload();
    }
}

You can also check for file size using file.size property.

您还可以使用 file.size 属性检查文件大小。