简体   繁体   中英

Best way to store model image using EF5 and retrieve in MVC View

I am looking for the best way to store image data in a model and then retrieve it in a view.

At the moment I have:

public class Product
{
  public int Id { get; set; }
  public byte[] Image { get; set; }
}

I then have a controller

public class ProductController
{
  public ActionResult List()
  {
    return View(Repository.GetAll())
  }
  public FileContentResult GetImage(int id)
  {
    Product p = Repository.GetById(id);
    return new FileContentResult(p.Image, "image/jpeg");
  }
}

A view...

@model IEnumerable<Product>
@foreach(var product in Model)
{
  <img src="@Url.Action("GetImage", "Person", new { id = item.Id })" alt="Person Image" />
}

What happens is as I get more and more products in the list, the images start to flash up on the screen as appose to loading instantly.

I am publishing to Azure so I can't really just go change byte[] to string and make string look in ~/Images/ProductImage.jpeg as I will have to publish the website every time I want to add a new product (as far as I am aware).

I am just looking for an alternative method of doing this or a reason why the images on my view appear gradually and flash up one after the other instead of instantly?

The images "flash" up instead of instantaneously because your browser has to return to the server for each image. Many browsers have a limit on how many extra links (css files, js files, image files, etc.) that it can have open at any given time. So that's why your images don't appear instantaneously.

Some things you can do to help:

  • If your images don't change often, add an [OutputCache(...)] attribute to your GetImage action. This way, the images will cache on the server and/or on the client for faster loading.
  • Store your files locally on the server instead of in a database. This will let your IIS access the files directly as static files and avoid the MVC pipeline.
  • Keep your files in the database, but cache them on your server (for example, under App_Data) as you retrieve them from the database. This avoids a database access.

Edit:

  • Store the image files in a publicly accessible (or semi-publicly) Azure blob. Your img src tags would point directly to the blob for access.

One of way of doing this would be to display the image directly from the byte array:

<img src="data:image/png; base64, @Convert.ToBase64String(product.Image)">

Should work for small images. You may also wish to store the image MIME so you can differentiate between data/png and data/jpg etc.

This should load the images immediately, as they will be part of the model sent to the view.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM