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

ndm*_*web 48 html5 file-upload fileapi

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

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

ps我知道我可以通过扫描.type属性在File API之后执行此操作.我真的试图限制这一点..我也知道我可以通过闪存做到这一点,但我不想为此使用闪存.

amo*_*era 63

这个特定目的有一个html属性,accept但它几乎没有跨浏览器的支持.因此建议使用此服务器端验证.

<input type="file" name="pic" id="pic" accept="image/gif, image/jpeg" />
Run Code Online (Sandbox Code Playgroud)

如果您无法访问后端,请查看基于闪存的解决方案,如SWFUpload.

在这里查看更多内容:文件输入'accept'属性 - 它有用吗?

  • 根据w3schools的说法,Internet Explorer 10,Firefox,Opera,Chrome和Safari 6都支持accept属性.没有指定Firefox,Opera或Chrome的版本号. (2认同)

Rad*_*ech 8

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

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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