Uploading a file with filtering its extension

12,641

Solution 1

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.

Solution 2

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

Solution 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" />
 }
Share:
12,641
Lamloumi Afif
Author by

Lamloumi Afif

Hi, I am a Software Development Engineer with a genuine interest in .Net framework. I enjoy reading books and practising sport. LinkedIn Viadeo

Updated on June 14, 2022

Comments

  • Lamloumi Afif
    Lamloumi Afif almost 2 years

    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?

  • Lamloumi Afif
    Lamloumi Afif almost 11 years
    yes i filtered it in the action, and i need to be in the view
  • YD1m
    YD1m almost 11 years
    Seems crome don't supports this correct MIME types. This markup accord to W3C spec
  • Circle Hsiao
    Circle Hsiao over 7 years
    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. Hope that help people stuck at old version like me.