Want to save a image to a folder and saving the url in database

前端 未结 2 485
灰色年华
灰色年华 2020-12-29 14:51

I very newbie in asp.net mvc . here I had a problem in the controller image upload anyone can give help ?? This example controller I get from the internet , what should I ch

2条回答
  •  情话喂你
    2020-12-29 15:17

    You should change your AvatarUrl to:

    public HttpPostedFileBase AvatarUrl { get; set; }
    

    In your view, you can create a form similar to the following. Add the fields you will accept input for and use a file input for your avatar. When the form is posted back to the controller, MVC will attempt to bind the inputs to the parameters.

    @using(Html.BeginForm("Create", FormMethod.Post, new { enctype = "multipart/form-data" }) {
        
    @Html.LabelFor(m => m.FirstName) @Html.EditorFor(m => m.FirstName)
    @Html.LabelFor(m => m.Avatar) @Html.EditorFor(m => m.Avatar)
    })

    Your controller method should be updated to:

    [HttpPost]
    public ActionResult Create(EmployeeModel model)
    {
        if (ModelState.IsValid)
        {
            // Create avatar on server
            var filename = Path.GetFileName(model.AvatarUrl.FileName);
            var path = Path.Combine(Server.MapPath("~/Uploads/Photo/"), filename);
            file.SaveAs(path);
            // Add avatar reference to model and save
            model.AvatarUrl = string.Concat("Uploads/Photo/", filename);
            _db.EventModels.AddObject(model);
            _db.SaveChanges();
    
            return RedirectToAction("Index");
        }
        return View(model);
    }
    

    If you're still stuck let me know and I can go into more detail.

    There's also an excellent/detailed write up related to what you're trying to do here http://cpratt.co/file-uploads-in-asp-net-mvc-with-view-models/

提交回复
热议问题