mvc4 或 html 5 中的文件输入过滤器?

Jam*_*123 4 html asp.net asp.net-mvc file-upload asp.net-mvc-4

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

但这些所有内容也显示“所有文件”选项。我想要严格限制某些文件类型,例如“*.pdf、所有 Office Word 类型、图像、Excel”。

我们怎样才能做到这一点?

我的代码就像

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

hut*_*oid 5

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

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

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

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

更新

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

private List<string> mimeTypes = new List<string> {
        "application/pdf", 
        "application/msword"
    };
Run Code Online (Sandbox Code Playgroud)

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

model.MimeTypes = string.Join(", ", mimeTypes);
Run Code Online (Sandbox Code Playgroud)

像这样渲染它们:

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