In my .Net MVC3 application, I am storing a few images into a SQL Server database (they are .png files). I would really like to stick with this method if possible, because I prefer working with a database to working with a filesystem (it’s a small page, and nobody will notice a performance issue).
Storing the image into the database seems to be no problem. Retrieving the data back out is not a problem either. What I’m having trouble with is displaying the image in a view.
The image is stored in a SQL Server database as a Varbinary(max). The View Model uses a Byte[] to hold the information. The View Model has other data stored in it, but as far as the image is concerned, here’s what I’ve done:
controller:
ViewModel data = Repository.GetData();
//data now holds all of the information that I need for my view
//data.Image is of type Byte[], and it holds the image I am having trouble displaying.
return View(data);
View
@model = data
@Html.DisplayFor(model => model.x) @*works*@
@Html.DisplayFor(model => model.Image) @*no good*@
Does the image need to be stored as a temp file in order for this to work?
If so, it seems like storing the image in the database is just a big waste of time.
If I return a FileStreamResult as my model:
FileStream fs = new FileStream(path, Open, Read);
return View(new FileStreamResult(fs, "image/png"));
….and I change my View’s model to be “FileStreamResult,” I can still find no way to display the image.
But if I return a FileStreamResult like this:
FileStream fs = new FileStream(path, Open, Read);
return new FileStreamResult(fs, "image/png");
then the image is displayed (but I think this is just the browser “opening” that file, not “rendering” it as html).
I know there are a lot of questions on this topic already, but I’ve looked at them. I think I’m missing some fundamental understanding of the web or mvc or something.
Thanks!
Option 1) ASP.NET MVC Custom Image Action
Option 2) In your view
< img src="loadimage?id=@Model.Id"/>And your controller: