Browse Upload Image in Mvc3
Step 1 : Use Form tag In View with post method
@using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data",id ="parentForm"}))
{
<input type="file" name="file />
<input type="submit" name="submit" value="submit" />
}
Step 2 : In Action Controller use HttpPostedFileBase
[HttpPost]
public ActionResult Create(Images image,HttpPostedFileBase file)
{
try
{
if (file != null)
{
if (file.ContentLength > 0)
{
if ((file.ContentType == "image/jpeg") || (file.ContentType == "image/gif") || (file.ContentType == "image/png"))//check allow jpg, gif, png
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Content/ProductImage/"), fileName);
file.SaveAs(path);//save image in folder
image.Link = file.FileName;
_database.Images.Add(image);//add Image object to database (content image path) _database.SaveChanges();
}
}
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
@using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data",id ="parentForm"}))
{
<input type="file" name="file />
<input type="submit" name="submit" value="submit" />
}
Step 2 : In Action Controller use HttpPostedFileBase
[HttpPost]
public ActionResult Create(Images image,HttpPostedFileBase file)
{
try
{
if (file != null)
{
if (file.ContentLength > 0)
{
if ((file.ContentType == "image/jpeg") || (file.ContentType == "image/gif") || (file.ContentType == "image/png"))//check allow jpg, gif, png
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Content/ProductImage/"), fileName);
file.SaveAs(path);//save image in folder
image.Link = file.FileName;
_database.Images.Add(image);//add Image object to database (content image path) _database.SaveChanges();
}
}
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
Thanks You Save my whole day To find on Internet.. ll wait for other posts like this.
ReplyDeleteI am glad that you liked my post...
Delete