ASP.Net MVC 5 image upload to folder

被刻印的时光 ゝ 提交于 2019-11-28 19:52:47
tvanfosson

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));
           }

           ....
      }
}

The code that was supplied here eventually went into building this small demo that allows you to upload images to the file system and use them dynamically without storing any values to the database; however you will have the string to the images file location as part of your Model class which uses a convention and naming of the uploaded file to display.

I would like to upload this to github and see if I can't get some others to help me work out a better solution that uses this idea. Thinking of making it work with MongoDB too.

ASP.NET MVC 5 Image Upload & Delete w/ Calculated Property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!