开发者

When I try insert picture from database to control - I get save picture in disk

开发者 https://www.devze.com 2023-02-01 06:06 出处:网络
I have this code to insert picture from database to image control: string strQuery = \"select Pic from MEN where id=\'1\'\";

I have this code to insert picture from database to image control:

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", 开发者_如何学Go"attachment;filename=" + dt.Rows[0]["PIC"].ToString());
   Response.BinaryWrite(bytes);
   Response.Flush();
   Response.End();
}

and this:

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

and this image:

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

but when I run this code I get "save picture on disk" and not insert to the image control

How to fix it ?

thanks


Try to remove:

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

also set the Response.ContentType to the mime type of the image, not to the filename. (here is the list of mime types: http://www.w3schools.com/media/media_mimeref.asp) and then tell us if it works

Another option would be to create an asp.net handler (.ashx) instead of an aspx page.

Sample here: http://msdn.microsoft.com/en-us/library/ms972953.aspx and here: http://aspalliance.com/1322_Displaying_Images_in_ASPNET_Using_HttpHandlers.all

0

精彩评论

暂无评论...
验证码 换一张
取 消