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

后端 未结 3 993
醉酒成梦
醉酒成梦 2020-11-27 06:23

Model

public partial class Assignment
{
    public Assignment()
    {
        this.CourseAvailables = new HashSet();
         


        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-27 06:44

    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"}))
    {
        ...
        
    <%: Html.TextBoxFor(model => model.FileLocation, new { type="file"})%> <%: Html.ValidationMessageFor(model => model.FileLocation) %>
    ... }

    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

提交回复
热议问题