MVC how to serve images to response stream

谁说我不能喝 提交于 2019-12-10 20:28:48

问题


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 $@product.LowestPrice
    }

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?


回答1:


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




回答2:


Ok finally figured it out thanks to DanNsk and this post here

public FileResult Image(string id)
{
    var dir = Server.MapPath("/content/images");
    var path = Path.Combine(dir, id);

    var stream = XTC.Helpers.ImageResizer.Resize( path, 150, 200);
    var result = new FileStreamResult(stream, "image/jpeg");

    return result;
}


来源:https://stackoverflow.com/questions/6473811/mvc-how-to-serve-images-to-response-stream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!