ASP.NET MVC 4 C# HttpPostedFileBase, How do I Store File

you can upload file and save its url in the database table like this:

View:

@using(Html.BeginForm("Create","Assignment",FormMethod.Post,new {enctype="multipart/form-data"}))
{
    ...
    <div class="editor-field">
        <%: Html.TextBoxFor(model => model.FileLocation, new { type="file"})%>
        <%: Html.ValidationMessageFor(model => model.FileLocation) %>
    </div>
    ...
}

Action:

[HttpPost]
public ActionResult Create(Assignment assignment)
{
    if (ModelState.IsValid)
    {
        if(Request.Files.Count > 0)
        {
            HttpPostedFileBase file = Request.Files[0];
            if (file.ContentLength > 0) 
            {
                var fileName = Path.GetFileName(file.FileName);
                assignment.FileLocation = Path.Combine(
                    Server.MapPath("~/App_Data/uploads"), fileName);
                file.SaveAs(assignment.FileLocation);
            }
            db.Assignments.Add(assignment);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
    }

    return View(assignment);
}

Details:

For better understanding refer this good article Uploading a File (Or Files) With ASP.NET MVC

Leave a Comment