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
I was looking all over the internet for two days to find this simple and only good answer till now. Thx a lot!!
ReplyDeleteWim
Nice to know...Good luck!
ReplyDeleteHi, I cant't get something similar to work. Could you please post the complete solution as a zip file? Thanks a lot.
ReplyDeleteAlexander
100% not working. plz help your src link is taking as string
ReplyDeleteThe "image/jpg" should do the trick, are you sure you included it in your code?
ReplyDeleteCertainly not working..............
ReplyDeleteIt is part of a working project....
ReplyDeleteWhat seem to be the problem?
I want to retrieve it from SQL SErver Database could you help ?
DeleteThat's what the sample is showing...notice the "create table" statement at the top.
DeleteCan u please provide the Demo Project......
ReplyDeleteCan you please provide the source code for the same
ReplyDeletegive me the complete source code for zip file
ReplyDeletegive me the complete source code for zip file
ReplyDeletemy emailid=veeeeeeeeeer@gmail.com
I tried to show image in view above way but its not showing
ReplyDeleteThis comment has been removed by the author.
ReplyDeletecan you solve my problem here I am pasting the link
ReplyDeletehttp://stackoverflow.com/questions/24567553/save-and-retrieve-image-from-database-using-spring-mvc-and-hibernate-rest-servic