2011-03-14 73 views
1

我无法弄清楚为什么当我尝试输出图像和一行文字时,我只能看到图像我做错了什么?Response.Write输出问题

 SqlConnection cn = new SqlConnection("CONNECTIONINFO HERE"); 

     SqlCommand cmd = new SqlCommand("SELECT * FROM test WHERE id=" + Request.QueryString["id"], cn); 

     cn.Open(); 
     SqlDataReader dr = cmd.ExecuteReader(); 
     if (dr.Read()) //check to see if image was found 
     { 
      Response.ContentType = dr["fileType"].ToString(); 
      Response.BinaryWrite((byte[])dr["imagesmall"]); 
      Response.Write("<br/>This is your image, if this is incorrect please contact the administrator."); 
     } 
     cn.Close(); 
+0

什么是ContentType设置为? – Patrick 2011-03-14 18:12:32

回答

1

为图像创建一个HttpHandler并从图像标签中调用它。

这样的:

public class ImageHandler : IHttpHandler 
{ 
    public bool IsReusable 
    { 
     get { return true; } 
    } 

    public void ProcessRequest(HttpContext context) 
    { 
     HttpRequest request = context.Request; 
     HttpResponse response = context.Response; 

     SqlConnection cn = new SqlConnection("CONNECTIONINFO HERE"); 
     SqlCommand cmd = new SqlCommand("SELECT * FROM test WHERE id=" + request.QueryString["id"], cn); 

     cn.Open(); 
     SqlDataReader dr = cmd.ExecuteReader(); 
     if (dr.Read()) //check to see if image was found 
     { 
      response.ContentType = dr["fileType"].ToString(); 
      response.BinaryWrite((byte[])dr["imagesmall"]); 
     } 
     cn.Close(); 
    } 
} 

然后使用它是这样的:

<img src="/ImageHandler.axd?id=1" /> 
<p>This is your image, if this is incorrect please contact the administrator.</p> 

您需要配置在web.config中或在IIS 7的处理程序,如果这是你使用的是什么。

方法如下:http://mvolo.com/blogs/serverside/archive/2007/08/15/Developing-IIS7-web-server-features-with-the-.NET-framework.aspx

+0

请您详细说明一下吗? – Patrick 2011-03-14 18:15:06

+0

我的初步答案有点短。我不得不让我的女孩睡觉:) – 2011-03-14 18:50:42

3

您正在将您的内容类型设置为二进制图像类型。浏览器很可能忽略了文本。如果您想在回复中同时使用这两种类型,则可能需要使用text/html作为响应类型,并使用<img>标签进行内嵌图像数据。

查看here查看内嵌图像数据的示例。

1

您不能将二进制响应与html内容响应混合在一起。如果你“保存”你的图像,你会注意到它是一个十六进制编辑器,它是二进制图像数据,你可以在文件末尾添加很少的html。

4

那么..内容类型大概是设置为像jpg,gif或其他一些图像类型的东西。我真的很惊讶,浏览器显示的图像,而不是错误。

要点是,你不能混合响应类型。

如果您必须显示文本,那么您需要发出一个普通的HTML文件,图像标签显示图像以及底部的相关文本。

0

你不说什么的ContentType设置为。如果它设置为'jpeg'或类似的话,那么你输出的HTML将不会被解释为HTML - 它只是更多的二进制数据。