(Preface: this question is about ASP.NET MVC 3.0 which was released in 2011, it is not about ASP.NET Core 3.0 which was released in 2019)
I want to
please pay attention this code for upload image only. I use HTMLHelper for upload image. in cshtml file put this code
@using (Html.BeginForm("UploadImageAction", "Admin", FormMethod.Post, new { enctype = "multipart/form-data", id = "myUploadForm" }))
{
@Html.UploadFile("UploadImage")
}
then create a HTMLHelper for Upload tag
public static class UploadHelper
{
public static MvcHtmlString UploadFile(this HtmlHelper helper, string name, object htmlAttributes = null)
{
TagBuilder input = new TagBuilder("input");
input.Attributes.Add("type", "file");
input.Attributes.Add("id", helper.ViewData.TemplateInfo.GetFullHtmlFieldId(name));
input.Attributes.Add("name", helper.ViewData.TemplateInfo.GetFullHtmlFieldName(name));
if (htmlAttributes != null)
{
var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
input.MergeAttributes(attributes);
}
return new MvcHtmlString(input.ToString());
}
}
and finally in Action Upload your file
[AjaxOnly]
[HttpPost]
public ActionResult UploadImageAction(HttpPostedFileBase UploadImage)
{
string path = Server.MapPath("~") + "Files\\UploadImages\\" + UploadImage.FileName;
System.Drawing.Image img = new Bitmap(UploadImage.InputStream);
img.Save(path);
return View();
}