Good way to retrieve images stored as bytes array in the db using ASP.NET MVC4?
.net, asp.net-mvc-4, c#
Solution
In your `HomeController` add a function like this:
[HttpGet]
public FileResult GetImage(string id)
{
byte[] fileContents = ...; // load from database or file system
string contentType = "image/jpeg";
return File(fileContents, contentType);
}
Register a route to this handler in `Global.asax.cs`:
routes.MapRoute(
"GetImage",
"img/{id}",
new { controller = "Home", action = "GetImage" });
In your webpage, use a `src` pointing to this action:
<img src="@Url.Action("GetImage", "Home", new { id = "logo.jpg" })" />
which will resolve to
<img src="/img/logo.jpg" />
Problem
I'm programming an ASP.NET MVC4 application which stores uploaded images as `byte[]` in a database (with Entity framework) and then displays them. To display the images I'm using this code in the view: ``` <img src="data:image;base64,@System.Convert.ToBase64String(item.ImageByte)" alt=""/> ``` But each time I refresh the page I see that the browser does not cache the image and just renders it again causing unecessary bandwith usage. Maybe there's a more bandwith friendlier way to display the image? Maybe the idea to store uploaded image as 'byte[]' was stupid in the first place (my application is just a simple web page which stores articles about psychology :D with an admin panel to achieve this) and I should just store images in a folder? Thanks