当我尝试从数据库插入图片来控制时 - 我在磁盘中保存图片

时间:2010-12-22 11:00:02

标签: c# asp.net

我有这个代码将数据库中的图片插入图像控件:

string strQuery = "select Pic from MEN where id='1'";
SqlCommand cmd = new SqlCommand(strQuery);
Convert.ToInt32(Request.QueryString["ImageID"]);
cmd.Parameters.Add("1", SqlDbType.Int).Value = Convert.ToInt32(Request.QueryString["ImageID"]);
DataTable dt = GetData(cmd);

if (dt != null)
{
   Byte[] bytes = (Byte[])dt.Rows[0]["Pic"];
   Response.Buffer = true;
   Response.Charset = "";
   Response.Cache.SetCacheability(HttpCacheability.NoCache);
   //Response.ContentType = dt.Rows[0]["ContentType"].ToString();
   Response.ContentType = dt.Rows[0]["PIC"].ToString();
   Response.AddHeader("content-disposition", "attachment;filename=" + dt.Rows[0]["PIC"].ToString());
   Response.BinaryWrite(bytes);
   Response.Flush();
   Response.End();
}

和此:

private DataTable GetData(SqlCommand cmd)
{
   DataTable dt = new DataTable();
   String strConnString = "server=" + Server + ";database=" + DataBase + ";UID=" + UID + ";password=" + PASS + ";";

   SqlConnection con = new SqlConnection(strConnString);
   SqlDataAdapter sda = new SqlDataAdapter();
   cmd.CommandType = CommandType.Text;
   cmd.Connection = con;

   try
   {
      con.Open();
      sda.SelectCommand = cmd;
      sda.Fill(dt);
      return dt;
   }
   catch
   {
      return null;
   }
   finally
   {
      con.Close();
      sda.Dispose();
      con.Dispose();
   }
}

和这张图片:

<asp:image ID="Image2" runat="server" ImageUrl ="PhoneBook.aspx?ImageID=1"/>

但是当我运行此代码时,我得到“将图片保存在磁盘上”而不是插入图像控件

如何解决?

感谢

1 个答案:

答案 0 :(得分:1)

尝试删除:

Response.AddHeader("content-disposition", "attachment;filename="+dt.Rows[0]["PIC"].ToString());

还将Response.ContentType设置为图像的mime类型,而不是文件名。 (这是mime类型列表:http://www.w3schools.com/media/media_mimeref.asp) 然后告诉我们它是否有效

另一种选择是创建一个asp.net处理程序(.ashx)而不是aspx页面。

此处示例:http://msdn.microsoft.com/en-us/library/ms972953.aspx 在这里:http://aspalliance.com/1322_Displaying_Images_in_ASPNET_Using_HttpHandlers.all