Can an ASP.NET MVC controller return an Image?

前端 未结 19 1677
旧时难觅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:55

    To expland on Dyland's response slightly:

    Three classes implement the FileResult class:

    System.Web.Mvc.FileResult
          System.Web.Mvc.FileContentResult
          System.Web.Mvc.FilePathResult
          System.Web.Mvc.FileStreamResult
    

    They're all fairly self explanatory:

    • For file path downloads where the file exists on disk, use FilePathResult - this is the easiest way and avoids you having to use Streams.
    • For byte[] arrays (akin to Response.BinaryWrite), use FileContentResult.
    • For byte[] arrays where you want the file to download (content-disposition: attachment), use FileStreamResult in a similar way to below, but with a MemoryStream and using GetBuffer().
    • For Streams use FileStreamResult. It's called a FileStreamResult but it takes a Stream so I'd guess it works with a MemoryStream.

    Below is an example of using the content-disposition technique (not tested):

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult GetFile()
        {
            // No need to dispose the stream, MVC does it for you
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data", "myimage.png");
            FileStream stream = new FileStream(path, FileMode.Open);
            FileStreamResult result = new FileStreamResult(stream, "image/png");
            result.FileDownloadName = "image.png";
            return result;
        }
    

提交回复
热议问题