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

前端 未结 3 1340
被撕碎了的回忆
被撕碎了的回忆 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 21:57

    I would go like this:

    in your model class:

     public class NewsItem
    {
        public virtual int Id { get; set; }
        public virtual string NewsTitle { get; set; }
        public virtual string NewsContent { get; set; }
        public virtual string NewsImage { get; set; } //string instead of byte because you don't wanna store your whole image file in your database, but just the path of the image, and the image you will store in a folder somewhere on the server
        public virtual DateTime DateAdded { get; set; }
        public virtual bool IsLive { get; set; }
    }
    

    in your controller:

    [Authorize]
        [HttpPost]
        public ActionResult Create(CreateNewsViewModel HttpPostedFileBase file)// add this 
        {
            if (ModelState.IsValid)
            {
                if (file != null)
                {
                    file.SaveAs(HttpContext.Server.MapPath("~/Images/") + file.FileName);
                    car.ImagePath = file.FileName;
                }
            // the rest of the code... 
    
            }
            else
            {
                return View(input);
            }
        }
    

    Then in your views you should have:

    for upload:

    <input id="NewsImage" title="Upload a image" type="file" name="file" />
    

    for display in the foreach cycle add:

    @Html.DisplayFor(modelItem => item.NewsImage)
    

    don't forget to add enctype = "multipart/form-data" in the Html.BeginForm

    I hope this would help.

    0 讨论(0)
  • 2020-12-20 22:00

    Have a look at jquery file uploader You can find sample code for it

    Hope this helps

    0 讨论(0)
  • 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:

    <input type="file" name="image" />
    

    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);
    
    0 讨论(0)
提交回复
热议问题