Search code examples
c#asp.net-mvcasp.net-mvc-3asp.net-mvc-4httppostedfilebase

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


Model

public partial class Assignment
{
    public Assignment()
    {
        this.CourseAvailables = new HashSet<CourseAvailable>();
    }

    public string AssignmentID { get; set; }
    public Nullable<System.DateTime> SubmissionDate { get; set; }
    public string Status { get; set; }
    public Nullable<decimal> Mark { get; set; }
    public string Comments { get; set; }
    public string FileLocation  { get; set; }
    public virtual ICollection<CourseAvailable> CourseAvailables { get; set; }
}}

Controller

 public ActionResult Create(Assignment assignment)
    {
        if (ModelState.IsValid)
        {


            db.Assignments.Add(assignment);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(assignment);
    }

View

<div class="editor-field">
    <%: Html.TextBoxFor(model => model.FileLocation, new { type="file"})%>
    <%: Html.ValidationMessageFor(model => model.FileLocation) %>
</div>

How do I store a file if I wanted to store the file into the server/path folder and in the database I only want to store the Path name/string.


Solution

  • 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