Display image from database in asp mvc

Viewed 90919

I'm getting an image in a byte array format from the controller, How can I display this in the view? in the simplest way.

6 Answers

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"] } ) %>' />

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))">

Assuming you have a dataRow (dr) with two columns, "name" and "binary_image" (binary_image contains the binary info)

 Byte[] bytes = (Byte[])dr["Data"];
 Response.Buffer = true;
 Response.Charset = "";

 Response.Cache.SetCacheability(HttpCacheability.NoCache);
 Response.ContentType = dr["Image/JPEG"].ToString();

 Response.AddHeader("content-disposition", "attachment;filename=" & dt.Rows[0]["Name"].ToString());

 Response.BinaryWrite(bytes);
 Response.Flush();
 Response.End(); 
Related