项目需要在MVC下显示图片
首先创建一个ImageResult
public class ImageResult : ActionResult { public ImageResult() { } public byte[] byteStream; //重写ExecuteResult public override void ExecuteResult(ControllerContext context) { // 设置响应设置 context.HttpContext.Response.ContentType = "image/jpeg"; context.HttpContext.Response.Cache.SetCacheability(System.Web.HttpCacheability.Public); context.HttpContext.Response.BufferOutput = false; // 将图像流写入响应流中 context.HttpContext.Response.OutputStream.Write(byteStream, 0, Convert.ToInt32(byteStream.Length)); }
在Controller的Action
public ActionResult GetImage(string imageUrl) { if (!System.IO.File.Exists(imageUrl)) { return null; } System.IO.FileStream fileStream = new System.IO.FileStream(imageUrl, System.IO.FileMode.Open); byte[] bytes = new byte[fileStream.Length]; fileStream.Read(bytes,0,bytes.Length); fileStream.Close(); return new ImageResult(){byteStream=bytes}; }
Html代码:
<img src="/Product/GetImage/?imageUrl=路径"/>