Display image from database in asp mvc

Create a controller for displaying images with a Show action that takes the id of the image to display from the database. The action should return a FileResult that contains the image data with the appropriate content type.

public class ImageController : Controller
{
    public ActionResult Show( int id )
    {
        var imageData = ...get bytes from database...

        return File( imageData, "image/jpg" );
    }
}

In your view, construct the image and use the image id to construct a path for the image using the controller and action.

<img src='<%= Url.Action( "show", "image", new { id = ViewData["imageID"] } ) %>' />

The accepted answer of using this:

<img src='<%= Url.Action( "show", "image", new { id = ViewData["imageID"] } ) %>'

is fine, but outdated for mvc 4. The updated syntax should now read:

<img src='@Url.Action( "show", "image", new { id = ViewData["imageID"] })' />

Also, I find that when I need this functionality I'm already passing other data to the view so it's nice to use the Model instead of the ViewData.

public class MyModel {
    public string SomeData {get;set;}
    public int FileId {get; set;}
}

From your controller:

public ActionResult Index() {
    MyEntity entity = fetchEntity();

    MyModel model = new MyModel {
        SomeData = entity.Data,
        FileId = entity.SomeFile.ID
    };

    return View(model);
}

Finally from your view:

<img src='@Url.Action("show", "image", new { id = Model.FileId })' />

The "Show" method on the controller for the accepted answer will work but I would change the hardcoded "image/jpg" to use File.ContentType - you can store this along with the byte[] so you don't need to guess if users are uploading their own images.


Every answer here may be correct but the simplest way from my opinion is get byte array or Model containing image and simply add like this

<img  src="data:image/jpeg;base64,@(Convert.ToBase64String(Model.Picture))">

Tags:

C#

Asp.Net Mvc