Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render image to the screen from MVC controller

I have images in the database and I want to return the image for viewing from an action. Here's my action.

public FileContentResult Index(ItemImageRequest request)
{
    var result = queueService.GetItemImage(request);

    if (result.TotalResults == 0)
        return File(new byte[0], "image/jpeg");

    var image = result.FirstResult;

    return File(image.Image, "image/tif");
}

I have also tried this code

public FileStreamResult Index(ItemImageRequest request)
{
    //retrieval omitted

    var image = result.FirstResult;

    System.IO.Stream stream = new System.IO.MemoryStream(image.Image);

    return new FileStreamResult(stream, "image/tif");
}

When I go to my action in the browser it prompts me for download. I don't want it to download, I want it to show in the browser. How do I accomplish this?

like image 729
Josh Avatar asked Dec 09 '22 10:12

Josh


1 Answers

If you use return Controller.File(filename, ...), you'll return a FilePathResult, which probably isn't what you want - I'm assuming that 'image' in your sample is an image filename (a case where 'var' isn't helping anyone...)

If you use one of the other File overloads, or use FileContentResult or FileStreamResult directly, you'll get the effect you want.

You don't need to make a custom ActionResult class (though of course, it might be useful for other reasons.)

HOWEVER, having just written all this, I've realised that your problem is that TIFF is not a file format which browsers can always (ever?) display internally, which is probably why they're prompting for a download.

You will need to re-render it to a PNG or something on the server to display in a browser.

like image 153
Will Dean Avatar answered Dec 19 '22 17:12

Will Dean