Web Api 返回图片流给前端

 

 

    public class TestController : ApiController
    {
        public HttpResponseMessage GetImg()
        {
            //获取文件的绝对路径
            string absolutePath = System.Web.Hosting.HostingEnvironment.MapPath("/img/woman.jpg");
            System.IO.FileStream fs = new System.IO.FileStream(absolutePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StreamContent(fs),
            };
            result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/jpg");

            //下面这行代码表示,弹出下载框,由用户选择需要保存的位置
            //如果不写,则直接打开该图片
            result.Content.Headers.ContentDisposition =
                new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
                {
                    //需要保存的图片的默认名字,如果不写,则默认提示为控制器名字,如本例为提示保存的名字为:"test"
                    FileName = "newWoman.jpg"
                };
            return result;
        }
    }

 

posted @ 2018-02-22 17:15  热敷哥  阅读(5673)  评论(0)    收藏  举报