Upload and Save Image file to Server Folder in ASP.Net MVC

Last Reply 7 months ago By kalpesh

Posted 7 months ago

i want on click of submit button image upload in directory and path of image save in in sql column

controller name is: store Action method is create image upload folder name : dynamicaimage

here is my create action method to insert data

[HttpPost]
            [ValidateAntiForgeryToken]
            public ActionResult Create([Bind(Include = "LanguageId,Image")] Store store, HttpPostedFileBase postedFile)
            {

                try
                {


                if (ModelState.IsValid && postedFile != null)
                {
                    string path = Server.MapPath("~/DynamicImage/");
                    db.Stores.Add(store);
                    db.SaveChanges();
                    postedFile.SaveAs(path + Path.GetFileName(postedFile.FileName));
                    ViewBag.Message = "File uploaded successfully.";
                    //return RedirectToAction("Index");
                }


                }
                catch (DataException)
                {

                    ModelState.AddModelError("", "Unable to save changes");
                }
                return View(store);
            }

html

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>


    @using (Html.BeginForm("Create", "Store", FormMethod.Post, new { enctype = "multipart/form-data" })) 
    {
        @Html.AntiForgeryToken()

        <div class="form-horizontal">
            <h4>Store</h4>
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model.LanguageId, "LanguageId", htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.DropDownList("LanguageId", null, htmlAttributes: new { @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.LanguageId, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.Image, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @*@Html.EditorFor(model => model.Image, new { htmlAttributes = new { @class = "form-control" } })*@
                    <input type="file" name="postedFile" />


                    @Html.ValidationMessageFor(model => model.Image, "", new { @class = "text-danger" })
                </div>
            </div>