ASP.Net MVC 5 image upload to folder

前端 未结 2 474
無奈伤痛
無奈伤痛 2020-12-14 04:48

I have a very simple MVC5 application that has a product page for the client that I also am utilizing the basic CRUD operations that have been scaffolded out in MVC 5.

2条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-14 05:00

    You'll need to:

    • add an input of type file to your form,
    • have the attribute on your form element enctype = "multipart/form-data"

    Then add an HttpPostedFileBase to your model with the same name as the name of the input. Then the HttpPostedFileModelBinder will populate the model property from the uploaded file before the action is invoked. Note, I think you should probably add in the model id somewhere, perhaps as a path element, to guaranteed uniqueness in the image path so that images don't accidentally get overwritten.

    There's a reasonably complete discussion of this at http://www.prideparrot.com/blog/archive/2012/8/uploading_and_returning_files

    public class Cakes
    {
        ...
    
        public HttpPostedFileBase UploadedFile { get; set; }
    
    }
    
    [HttpPost]
    public ActionResult Edit(Cakes cake) // I'd probably use a view model here, not the domain model
    {
          if (ModelState.IsValid)
          {
               if (cakes.UploadedFile != null)
               {
                   cakes.UploadedFile.SaveAs(Path.Combine("path-to-images-for-this-cake", cakes.CakeImage));
               }
    
               ....
          }
    }
    

提交回复
热议问题