简体   繁体   中英

File input filters in mvc4 or html 5?

I know that we can use filter types in HTML 5 with accept attribute <input accept="audio/*|video/*|image/*|MIME_type">

But these all things are showing "All Files" options too. I want strict to certain file types in the like "*.pdf, All office word types, images, excel".

How can we do that?

My Code like

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

You simply replace your accept(s) with the full mime type in your case application/pdf rather than the wildcard *.

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

You can separated multiple mime type with a comma, if you wanted pdf and word in a single upload control you would do so like this:

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

Update

If you store your accepted mime types in a collection (hard-coded here for demo purposes)

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

You can add the accepted mime type to your model, return them like this:

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

Render them like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM