【问题标题】:File input filters in mvc4 or html 5?mvc4 或 html 5 中的文件输入过滤器?
【发布时间】:2014-02-27 11:43:40
【问题描述】:

我知道我们可以在 HTML 5 中使用带有接受属性 <input accept="audio/*|video/*|image/*|MIME_type"> 的过滤器类型

但是所有这些都显示“所有文件”选项。我想严格限制某些文件类型,例如“*.pdf、所有办公文字类型、图像、excel”。

我们该怎么做?

我的代码喜欢

  @Html.TextBoxFor(m => m.Attachment, new { @class = "form-control", type = "file" })

【问题讨论】:

    标签: asp.net asp.net-mvc html asp.net-mvc-4 file-upload


    【解决方案1】:

    您只需将您的接受替换为您的案例应用程序/pdf 中的完整 mime 类型,而不是通配符 *。

    @Html.TextBoxFor(m => m.Attachment, new { @class = "form-control", type = "file", accept="application/pdf" })
    

    您可以用逗号分隔多个 mime 类型,如果您想在一个上传控件中使用 pdf 和 word,您可以这样做:

    @Html.TextBoxFor(m => m.Attachment, new { @class = "form-control", type = "file", accept="application/pdf, application/msword" })
    

    更新

    如果您将接受的 mime 类型存储在集合中(此处为演示目的硬编码)

    private List<string> mimeTypes = new List<string> {
            "application/pdf", 
            "application/msword"
        };
    

    您可以将接受的 mime 类型添加到您的模型中,像这样返回它们:

    model.MimeTypes = string.Join(", ", mimeTypes);
    

    像这样渲染它们:

    @Html.TextBoxFor(m => m.Attachment, new { @class = "form-control", type = "file", accept=Model.MimeTypes })
    

    【讨论】:

    • 如果我想要“pdf、word、excel、jpg、gif”,但不是所有文件怎么办??
    • 您可以简单地附加它们,但用逗号分隔它们,即 application/pdf, application/vnd.ms-word.document
    • 出于安全原因,我还会确保您也在服务器端检查它们。
    • 您必须根据文件扩展名选择您的 mime 类型,这适用于带有 .doc 扩展名的 word 文档。 jsfiddle.net/VCdvA/1062这对你有好处吗?
    • 这很好。它仍然在下拉列表中显示“所有文件”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-27
    • 1970-01-01
    • 2014-02-05
    • 2011-04-25
    • 1970-01-01
    • 1970-01-01
    • 2019-01-17
    相关资源
    最近更新 更多