3

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?

Subby
  • 5,370
  • 15
  • 70
  • 125
  • "file" is too undefined for the extend use you give it here. Why don't you try to use "uploadedFile" or something like that on the input type file and on the controller parameter? – Bardo Sep 24 '12 at 10:56
  • Check my answer in http://stackoverflow.com/questions/16102235/upload-image-mvc-always-null – flygge Jan 26 '14 at 16:38

2 Answers2

4

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");
}
Akash KC
  • 16,057
  • 6
  • 39
  • 59
1

Was having the same problem then realized I had not specified ( enctype = "multipart/form-data") in my form

cgitosh
  • 313
  • 3
  • 12