MVC how to serve images to response stream

10,702

Get Route/Action link on new action which downloads an image to set as image url,

<img src='@Url.RouteUrl("Full", new { action = "Image", controller = "Media", number = product.id })' />

or

<img src='@Url.Action("Image", new { number = 3 })' />

Add new action which has something like

public ActionResult Image(int? number)
{
    var media = mr.GetMedia(number);

    return base.File(media.Content, media.ContentType ?? "image/jpeg");
}

where media.Content is binary content or stream reference

Share:
10,702
StuTheDog
Author by

StuTheDog

Senior Software Engineer developing apps and support for mobile applications. Primary development focus is Android (Java/C++) and Web (ASP.NET/MVC/C#).

Updated on June 04, 2022

Comments

  • StuTheDog
    StuTheDog almost 2 years

    In my controller I retrieve a list of products along with an image name, then scale the image down to the size needed by the view. The images are now in memory, ready to be written to the response stream. I know the client will send a response for each image but I have no idea how to hook into it to provide the image.

    View code:

        @foreach (var product in Model.Products)
        {
           @product.Name
           <img src="@product.Thumbnail"/>
           Priced From [email protected]
        }
    

    Controller:

        model.Products =
           DataContext.Products.Where(p => p.Category.Name
                .Equals(id)).Select(m => new ProductListItem
                    {
                       Name = m.Name,
                       Thumbnail = ImageResizer.Resize(m.Image, 75, 100, <normally I put the output stream here>),
                       LowestPrice = SqlFunctions.StringConvert( m.PriceSet.Prices.Min(p =>p.Price1))
                    }
        );
    

    Where ImageResizer.Resize() signature is

    Resize(string imageName, int width, int height, Stream outputStream)
    

    So my question I think should be- what do I put in for the image name and how do I listen for requests for each image that can be written to the stream?