1

我不明白为什么当我尝试在下面输出图像和一行文本时,我只得到图像我做错了什么?

        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();
4

5 回答 5

4

嗯.. 内容类型大概设置为 jpg、gif 或其他图像类型。我真的很惊讶浏览器显示图像而不是出错。

关键是,您不能混合响应类型。

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

于 2011-03-14T18:12:51.337 回答
3

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

有关内联图像数据的示例,请参见此处。

于 2011-03-14T18:12:03.340 回答
1

您不能将二进制响应与 html 内容响应混合。如果您“保存”您的图像,您会在十六进制编辑器中注意到它是二进制图像数据,您的小片段 html 附加到文件末尾。

于 2011-03-14T18:12:07.443 回答
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

于 2011-03-14T18:13:36.643 回答
0

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

于 2011-03-14T18:13:40.593 回答