【问题标题】:restrict file upload selection to specific types将文件上传选择限制为特定类型
【发布时间】:2011-11-26 09:22:46
【问题描述】:

是否通过<input type="file" /> 元素限制文件类型的选择?

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

附言我知道我可以在使用 File API 通过扫描 .type 属性之后做到这一点。我真的想事先限制这一点。我也知道我可以通过 flash 做到这一点,但我不想为此使用 flash。

【问题讨论】:

    标签: html file-upload fileapi


    【解决方案1】:

    有一个用于此特定目的的 html 属性称为accept,但它几乎不支持跨浏览器。因为这个服务器端验证是推荐的。

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

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

    在此处查看更多信息:File input 'accept' attribute - is it useful?

    【讨论】:

    • 根据 w3schools the accept attribute is supported in Internet Explorer 10, Firefox, Opera, Chrome, and Safari 6. 未指定 Firefox、Opera 或 Chrome 的版本号。
    【解决方案2】:

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

    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();
        }
    }
    

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

    【讨论】:

    • 问题是关于如何去做,而不是如果你认为这是继续的好方法。
    猜你喜欢
    • 2018-06-15
    • 2018-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-16
    • 2021-10-14
    • 2023-03-22
    • 1970-01-01
    相关资源
    最近更新 更多