I tried to have an images uploader but when I click the browse and select image then submit my form the HttpPostedFileBase is null. Is there missing with my implementation? Please help.
View
<form action="Home/UploadImage" method="POST">
<p>
<input type="file" accept="image/x-png, image/gif, image/jpeg" name="projectBgImage" id="projectBgImage"/>
</p>
<input type="submit" value="submit"/>
</form>
Home Controller
public ActionResult UploadImage(HttpPostedFileBase projectBgImage)
{
return View();
}
Debug Image
add enctype attribute
your form
element
<form action="Home/UploadImage" method="POST" enctype="multipart/form-data">
I suggest you to use BeginForm
html-helper like this:
@using (Html.BeginForm("UploadImage", "Home", FormMethod.Post, new { id = "form", enctype="multipart/form-data" }))
{
<p>
<input type="file" accept="image/x-png, image/gif, image/jpeg" name="projectBgImage" id="projectBgImage"/>
</p>
<input type="submit" value="submit"/>
}
and Action Method with [HttpPost]
annotation
[HttpPost]
public ActionResult UploadImage(HttpPostedFileBase projectBgImage)
{
return View();
}
Extra Information : A nice blog post by Phil Haack Asp.net MVC Upload
In the View an enctype
attribute is required to be set to multipart/form-data
using (Html.BeginForm("ImageUp", "YourUpController", FormMethod.Post, new { enctype = "multipart/form-data" }))
Second,
On top of your action method make sure you have the HTTPPOST
attribute.
[HttpPost]
public ActionResult SaveFile(HttpPostedFileBase projectBgImage)