Sidharth Sharma
Sidharth Sharma

Reputation: 19

Unable to save my image in a folder using ASP.NET MVC

I have tried this code but I'm unable to save the image/file in the specified folder. What is wrong with the code?

Controller:

public ActionResult Work(Work workmodel, HttpPostedFileBase workpostpath)
{
    if (workpostpath != null)
    {
        // Upload your service images
        using (entities = new saabinteriormodel())
        {
            string workpic = System.IO.Path.GetFileName(workpostpath.FileName);
            string workpath = System.IO.Path.Combine(Server.MapPath("~/Content/Images/work/"), workpic);

            workpostpath.SaveAs(workpath);

            Work work = new Work
            {
                work_image = "~/Content/Images/work/" + workpic};
                workmodel.work_image = work.work_image;
                entities.Works.Add(work);
                entities.SaveChanges();
            }
        }

        return View();
    }
}

View:

@using (Html.BeginForm ("Work", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
    <input id="uploadimage" type="file" />
    @ViewBag.Message
    <input id="work" type="submit" value="Save Work"/>
}

Thank you.

Upvotes: 0

Views: 279

Answers (1)

IGeoorge
IGeoorge

Reputation: 160

you're creating a new record in db, but not saving posted files anywhere. try

workpostpath.SaveAs(Server.MapPath("~/folder/file.extension"));

Alsou you could retrieve the posted files from request

HttpPostedFileBase file = Request.Files[0];

Upvotes: 1

Related Questions