Can an ASP.NET MVC controller return an Image?

前端 未结 19 1641
旧时难觅i
旧时难觅i 2020-11-22 02:10

Can I create a Controller that simply returns an image asset?

I would like to route this logic through a controller, whenever a URL such as the following is requeste

19条回答
  •  感情败类
    2020-11-22 02:44

    UPDATE: There are better options than my original answer. This works outside of MVC quite well but it's better to stick with the built-in methods of returning image content. See up-voted answers.

    You certainly can. Try out these steps:

    1. Load the image from disk in to a byte array
    2. cache the image in the case you expect more requests for the image and don't want the disk I/O (my sample doesn't cache it below)
    3. Change the mime type via the Response.ContentType
    4. Response.BinaryWrite out the image byte array

    Here's some sample code:

    string pathToFile = @"C:\Documents and Settings\some_path.jpg";
    byte[] imageData = File.ReadAllBytes(pathToFile);
    Response.ContentType = "image/jpg";
    Response.BinaryWrite(imageData);
    

    Hope that helps!

提交回复
热议问题