http://localhost:40469/1.jpg 返回值是200,但图片就是无法显示,多尴尬啊!

如果通过后台程序让图片在浏览器里显示呢?

1、根据现有图片路径,构造出html

2、根据现有图片路径,将其写入http响应输出流里

3、动态的构造出一张图片,再将其保存到http响应输出流里

 

 public void ProcessRequest(HttpContext context)
        {          
    
            context.Response.ContentType = "text/html";
            string html = "<img src=\"/upload/desert.jpg\" />";
            context.Response.Write(html);
           
        }
 public void ProcessRequest(HttpContext context)
        {
          
            context.Response.ContentType = "image/jpeg";

            context.Response.WriteFile("/upload/desert.jpg");          
          
        }

这2中方式都可以,在平时肯定都能够显示图片,可是我前几天无意间在web.config里注册了一个HttpMoudle,当时只是测试而已,就随意输出了几句话,正是这几句,才导致了,图片不能显示。

 public class MyModule : IHttpModule
    {
        public void Dispose()
        {

        }

        public void Init(HttpApplication applcation)
        {
            applcation.BeginRequest += new EventHandler(Application_BeginRequest);
            applcation.EndRequest += (sender, e) => { applcation.Context.Response.Write("1"); };
            applcation.PreSendRequestHeaders += (sender, e) => { applcation.Context.Response.Write("2"); };
            applcation.PreSendRequestContent += (sender, e) => { applcation.Context.Response.Write("3"); };
        }

        public void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpApplication ha = sender as HttpApplication;          
            ha.Context.Response.ContentType = "text/plain";
            ha.Context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
            ha.Context.Response.Write("啦啦啦");
        }
    }

就因为我在管道的一开始就注册了一个beginrequest事件,并在里面输出了一段文本“啦啦啦”,所以,在http中在请求这个图片的时候,也是先走这个beginrequest事件,然后输出了“啦啦啦”,然后再去加载图片,此时的图片的二进制已经多了啦啦啦这个文本,破坏了原来的图片的二进制,所以图片是不会显示的,太坑了。

 

第一种方式会输出

因为:先请求ashx页,会输出

然后再去走一遍管道事件去请求图片地址,此时再缓存区里有了“啦啦啦”,然后图片报错无法显示。

 

 

第二种方式,页面上只有一个不显示的图片,并没有啦啦啦这个文本,原因很简单,尽管在响应的缓存区里已经有了啦啦啦,但是它要求响应的格式是image,当输出缓存区的数据到浏览器的时候,二进制被破坏肯定不会显示图片,同时后面的httpmoudle里的 1,2,3也不会显示。

 

posted on 2017-05-09 10:58  奔游浪子  阅读(2723)  评论(0)    收藏  举报

导航