3

I have an ASP.Net web application in which i have to upload a file:

@using (Html.BeginForm("Uploading_validation", "Super", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <input type="file" name="dossier"  accept="*.iso, *.rar, *.zip"/>
   <br />
    @Html.Label("Date d'expiration")

    <input type="text" id="datepicker" name="duree" />
    <br />
 <input type="submit" value="OK" />
 }

I'd like accept just the extensions accept="*.iso, *.rar, *.zip", but it didn't work.

Why does this filter not work? How can i modify the code?

Sam
  • 7,252
  • 16
  • 46
  • 65
Lamloumi Afif
  • 8,941
  • 26
  • 98
  • 191

3 Answers3

9

You can use the FileExtensions to achieve this:

[Required, FileExtensions(Extensions=".iso,.rar,.zip", ErrorMessage="Incorrect file format")]

Add Dossier to your model to pass it back to the view and render it like this:

    @Html.TextBoxFor(m => m.Dossier, new { type = "file" })
    @Html.ValidationMessageFor(m => m.Dossier)

It should validate both client and server-side.

hutchonoid
  • 32,982
  • 15
  • 99
  • 104
  • I'm using MVC 4 for a project and this solution invalid not matter my extension is correct or not. Finally solved the issue by [this.](http://stackoverflow.com/questions/8536589/asp-net-mvc-3-dataannotations-fileextensionsattribute-not-working/13650754#13650754) Hope that help people stuck at old version like me. – Circle Hsiao Jan 12 '17 at 08:54
3

accept attribute don't supported by all of browsers. You can't rely on client side and should filter files in action.

BTW, you should use this attribute this way:

accept="application/iso,application/rar,application/zip"

Upd: in other way you can validate file extension with javascript: look at sample

YD1m
  • 5,845
  • 2
  • 19
  • 23
3

this snippet seems to be acceptable by all browsers

@using (Html.BeginForm("Uploading_validation", "Super", FormMethod.Post, new { enctype = "multipart/form-data" }))
{

    <input type="file" name="dossier"   accept=".rar , .zip"/>
   <br />
    @Html.Label("Date d'expiration")

    <input type="text" id="datepicker" name="duree" />
    <br />
 <input type="submit" value="OK" />
 }
Lamloumi Afif
  • 8,941
  • 26
  • 98
  • 191