Monday, September 20, 2010

Displaying images from a database - MVC style

Exploring MVC 2 I started a small project that included displaying images from my database, I know this is quite the basics, but I was impressed of the simplicity & elegant style this simple task gets when using MVC.

In the database I have a table that includes images contained in varbinary(max) column.

CREATE TABLE [dbo].[Album](
[AlbumId] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](max) NOT NULL,
[Picture] [varbinary](max) NULL,
...
...
CONSTRAINT [PK_Album] PRIMARY KEY CLUSTERED 
(
[AlbumId] ASC
)


Next in my data access layer I've added a linq query to retrieve an image by albumId.

public byte[] GetAlbumCover(int albumId)
{
var q = from album in _db.Album
where album.AlbumId == albumId
select album.Picture;

byte[] cover = q.First();

return cover;
}


As for the actual MVC...

The controller:
public ActionResult RetrieveImage(int id)
{
byte[] cover = _BL.GetAlbumCover(id);

if (cover != null)
return File(cover, "image/jpg");

return null;
}


The view:
<% foreach (var item in Model) { %>

<tr>
<td>
<%: item.ArtistName %>
</td>
<td>
<%: item.AlbumName %>
</td>
<td>
<img src="/MusicInfo/RetrieveImage/<%:item.AlbumId%>"  alt="" height=100 width=100/>
</td>
<td>
<%: Html.ActionLink("Edit", "Edit", new {id=item.AlbumId}) %>
</td>
</tr>

<% } %>


The link of the picture points to the controller (MusicInfo), the method inside the controller (RetrieveImage) & the specific image id to be able to retrieve it.

That's it...simple yet elegant.

Till next time
Diego

14 comments:

  1. I was looking all over the internet for two days to find this simple and only good answer till now. Thx a lot!!

    Wim

    ReplyDelete
  2. Hi, I cant't get something similar to work. Could you please post the complete solution as a zip file? Thanks a lot.

    Alexander

    ReplyDelete
  3. 100% not working. plz help your src link is taking as string

    ReplyDelete
  4. The "image/jpg" should do the trick, are you sure you included it in your code?

    ReplyDelete
  5. Certainly not working..............

    ReplyDelete
  6. It is part of a working project....
    What seem to be the problem?

    ReplyDelete
  7. Can u please provide the Demo Project......

    ReplyDelete
  8. Can you please provide the source code for the same

    ReplyDelete
  9. give me the complete source code for zip file

    ReplyDelete
  10. give me the complete source code for zip file
    my emailid=veeeeeeeeeer@gmail.com

    ReplyDelete
  11. I tried to show image in view above way but its not showing

    ReplyDelete
  12. This comment has been removed by the author.

    ReplyDelete
  13. can you solve my problem here I am pasting the link

    http://stackoverflow.com/questions/24567553/save-and-retrieve-image-from-database-using-spring-mvc-and-hibernate-rest-servic

    ReplyDelete