ASP.NET MVC HttpPostedFIleBase is null

Subby picture Subby · Sep 24, 2012 · Viewed 7.2k times · Source

I have a @Html.BeginForm in my view which is suppose to allow the user to upload an image and add some details about the image.

Here is the View:

@Html.BeginForm("SaveImage", "Listing", FormMethod.Post, new { enctype = "multipart/form-data" }))) {
<div id="modalAddImage" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                    <h3 id="myModalLabel">Modal header</h3>
    </div>
    <div class="modal-body">
    <p>Image</p>
    <input type="file" name="file"></input>

     @foreach (Image translation in Model.Listing.Images)
     {
        @Html.TextBoxFor(m => m.Description)
     }
     </div>
     <div class="modal-footer">
     <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
     <button class="btn btn-primary">Save changes</button>
 </div>
</div>
}

I have a different @Html.BeginForm right before this one which is for something else.

This is my controller:

    [HttpPost]
    public ActionResult SaveImage(HttpPostedFileBase file)
    {
        if (file!= null && file.ContentLength > 0)
        {
            var fileName = Path.GetFileName(file.FileName);
            var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
            file.SaveAs(path);
        }

        return View("Maintain");
    }

When I put a break-point in SaveImage, file is always null. I have tried to upload both big and small images.

Can anyone see where I am going horribly wrong?

Answer

Akash KC picture Akash KC · Sep 24, 2012

You can simply do like this:

[HttpPost]
public ActionResult SaveImage(HttpPostedFileBase file)
{
     if (Request.Files.Count > 0)
     {
        foreach (string upload in Request.Files)
        {
           if (upload != null)
           {
              var fileName = Path.GetFileName(file.FileName);
              var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);      
              Request.Files[upload].SaveAs(path);

           }
        }
     }
    return View("Maintain");
}