How to upload/display images using ASP.net MVC4 with Entity Framework

前端 未结 3 1352
被撕碎了的回忆
被撕碎了的回忆 2020-12-20 21:30

I have a data model like so

    public class NewsItem
{
    public virtual int Id { get; set; }
    public virtual string NewsTitle { get; set; }
    public         


        
3条回答
  •  半阙折子戏
    2020-12-20 22:05

    You'll want an input field of type file to upload from the View and an instance of the WebImage to handle the uploaded image:

    View:

    
    

    Controller:

    WebImage image = WebImage.GetImageFromRequest();
    byte[] toPutInDb = WebImage.GetBytes();
    
    // ... put the byte array into the database
    

    To display the images from your database, you will want a controller Action that retrieves the byte array from your database and returns a FileAction. You can get this image (for the image retrieving controller action) by instantiating another WebImage instance on the bytearray you retrieve from database:

    WebImage image = new WebImage(byteArrayFromDb);
    
    File(image.GetBytes(), "image/" + image.ImageFormat, image.FileName);
    

提交回复
热议问题