Alexis Alexis - 4 months ago 56
ASP.NET (C#) Question

ASP .NET upload file null HttpPostedFileBase

i'm trying to upload file from a form using ASP MVC 5.

But my file.ContentLength is always = 0...

public ActionResult Test(int? id, HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
//blabla
}
}


and here my form in .cshtml

using (Html.BeginForm("Test", "MyController",FormMethod.Post, new { id = Model.Id, enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()

<input type="file" id="file" name="file" />
<br />
<div class="form-group">
<button type="submit">Ajouter</button>
</div>

}

Answer

Use this :

var count = Request.Files.Count;

if (count > 0) {
   var files = Request.Files[0];
   if(files.ContentLength > 0){
       Your work here e.g : string name = files.FileName ....
   }
}

Snapshot :

Working example

Comments