Response.ContentType = "image/bmp";

解决方案 »

  1.   

    给你贴个代码:
    ---------------------------imgupload.aspx------------------------------------
    <%@ Page language="c#" Codebehind="imgupload.aspx.cs" AutoEventWireup="false" Inherits="study.uploadimage.imgupload" %>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
    <HTML>
    <HEAD>
    <title>imgupload</title>
    <meta name="GENERATOR" Content="Microsoft Visual Studio 7.0">
    <meta name="CODE_LANGUAGE" Content="C#">
    <meta name="vs_defaultClientScript" content="JavaScript">
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
    </HEAD>
    <body>
    <form enctype="multipart/form-data" runat="server" id="form1" name="form1">
    文件名 <input type="text" id="imgName" runat="server" NAME="imgName">
    <br>
    选择文件 <input id="UploadFile" type="file" runat="server" NAME="UploadFile">
    <br>
    <asp:button Text="上传" runat="server" ID="Button1" />
    </form>
    <a href="imgview.aspx?id=1" target=_blank>看图</a>
    </body>
    </HTML>------------------------------imgupload.aspx.cs---------------------------
    using System;
    using System.Collections;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Web;
    using System.Web.SessionState;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.HtmlControls;
    using System.IO;
    using System.Data.SqlClient;namespace study.uploadimage
    {
    /// <summary>
    /// imgupload 的摘要说明。
    /// </summary>
    public class imgupload : System.Web.UI.Page
    {
    protected System.Web.UI.WebControls.Button Button1;
    protected System.Web.UI.HtmlControls.HtmlInputText imgName;
    protected System.Web.UI.HtmlControls.HtmlInputFile UploadFile;

    private void Page_Load(object sender, System.EventArgs e)
    {
    // 在此处放置用户代码以初始化页面
    } private void Button1_Click(object sender, System.EventArgs e)
    {
    Stream imgStream;
    int imgLen;
    string imgName_value;
    string imgContentType;
    string imgUploadedName;

    imgStream  = UploadFile.PostedFile.InputStream;
    imgLen =  UploadFile.PostedFile.ContentLength;
    imgUploadedName = UploadFile.PostedFile.FileName;
    byte[] imgBinaryData=new byte[imgLen];
    imgContentType = UploadFile.PostedFile.ContentType;
    imgName_value = imgName.Value; try
    {
    if(imgName_value.Length < 1)
    {
    imgName_value = GetLastRightOf("\\",imgUploadedName );
    }
    }
    catch(Exception myEx)
    {
    Response.Write(myEx.Message);
    } int n = imgStream.Read(imgBinaryData, 0, imgLen);          
    int NumRowsAffected = MyDatabaseMethod(imgName_value, imgBinaryData, imgContentType);
                if(NumRowsAffected > 0)
                Response.Write( "<BR> uploaded image " );
    else
                Response.Write ( "<BR> an error occurred uploading the image.d " );
    }
    public string GetLastRightOf(string LookFor,string myString)
    {
    int StrPos;
    StrPos = myString.LastIndexOf(LookFor);
    return myString.Substring(StrPos + 1);
    }
    public int MyDatabaseMethod(string imgName,byte[] imgbin,string imgcontenttype)
    {
    SqlConnection connection = new SqlConnection(Application["Test_Conn"].ToString());
    string SQL="INSERT INTO Image (img_name,img_data,img_contenttype) VALUES ( @img_name, @img_data,@img_contenttype )";
    SqlCommand command=new SqlCommand ( SQL,connection );
                
    SqlParameter param0=new SqlParameter ( "@img_name", SqlDbType.VarChar,50 );
    param0.Value = imgName;
    command.Parameters.Add( param0 );             SqlParameter param1=new SqlParameter ( "@img_data", SqlDbType.Image );
    param1.Value = imgbin;
    command.Parameters.Add( param1 );
                
    SqlParameter param2 =new SqlParameter ( "@img_contenttype", SqlDbType.VarChar,50 );
    param2.Value = imgcontenttype;
    command.Parameters.Add( param2 );

    connection.Open();
    int numRowsAffected = command.ExecuteNonQuery();
    connection.Close();
    return numRowsAffected;
    } #region Web Form Designer generated code
    override protected void OnInit(EventArgs e)
    {
    //
    // CODEGEN:该调用是 ASP.NET Web 窗体设计器所必需的。
    //
    InitializeComponent();
    base.OnInit(e);
    }

    /// <summary>
    /// 设计器支持所需的方法 - 不要使用代码编辑器修改
    /// 此方法的内容。
    /// </summary>
    private void InitializeComponent()
    {    
    this.Button1.Click += new System.EventHandler(this.Button1_Click);
    this.Load += new System.EventHandler(this.Page_Load); }
    #endregion
    }
    }
    --------------------------------imgview.aspx--------------------------------
    <%@ Page language="c#" Codebehind="imgview.aspx.cs" AutoEventWireup="false" Inherits="study.uploadimage.imgview" %>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
    <HTML>
    <HEAD>
    <title>imgview</title>
    <meta name="GENERATOR" Content="Microsoft Visual Studio 7.0">
    <meta name="CODE_LANGUAGE" Content="C#">
    <meta name="vs_defaultClientScript" content="JavaScript">
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
    </HEAD>
    <body MS_POSITIONING="GridLayout">
    <form id="imgview" method="post" runat="server">
    <asp:textbox id="text1" runat="server" />
    </form>
    </body>
    </HTML>
    --------------------------imgview.aspx.cs----------------------------------
    using System;
    using System.Collections;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Web;
    using System.Web.SessionState;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.HtmlControls;
    using System.Data.SqlClient;namespace study.uploadimage
    {
    /// <summary>
    /// imgview 的摘要说明。
    /// </summary>
    public class imgview : System.Web.UI.Page
    {
    protected System.Web.UI.WebControls.TextBox text1;

    private void Page_Load(object sender, System.EventArgs e)
    {
    SqlConnection myDSN = new SqlConnection(Application["Test_Conn"].ToString());
    myDSN.Open(); int imgid = int.Parse(Request.QueryString["id"]);
    string sqlText = "SELECT img_name, img_data, img_contenttype FROM image where img_pk=" + imgid;
    Trace.Write(sqlText);
    SqlCommand MyCommand = new SqlCommand (sqlText, myDSN);
    SqlDataReader dr =MyCommand.ExecuteReader();
    if(dr.Read())
    {
    Response.ContentType = (dr["img_contenttype"].ToString());
    Response.BinaryWrite((byte[])dr["img_data"]);
    }
    myDSN.Close();
    } #region Web Form Designer generated code
    override protected void OnInit(EventArgs e)
    {
    //
    // CODEGEN:该调用是 ASP.NET Web 窗体设计器所必需的。
    //
    InitializeComponent();
    base.OnInit(e);
    }

    /// <summary>
    /// 设计器支持所需的方法 - 不要使用代码编辑器修改
    /// 此方法的内容。
    /// </summary>
    private void InitializeComponent()
    {    
    this.Load += new System.EventHandler(this.Page_Load); }
    #endregion
    }
    }
    ---------------------------image.sql----------------------------------------
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[image]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[image]
    GOCREATE TABLE [dbo].[image] (
    [img_pk] [int] IDENTITY (1, 1) NOT NULL ,
    [img_name] [varchar] (50) NULL ,
    [img_data] [image] NULL ,
    [img_contenttype] [varchar] (50) NULL 
    ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
    GOALTER TABLE [dbo].[image] WITH NOCHECK ADD 
    CONSTRAINT [PK_image] PRIMARY KEY  NONCLUSTERED 
    (
    [img_pk]
    )  ON [PRIMARY] 
    GO
      

  2.   


    Response.BinaryWrite((byte[])dr["img_data"]);我一加这句话,编译并启动的时候,他就让我下载,不知道为什么有没有更好的方法呢?
      

  3.   

    Response.ContentType = "image/*";
      

  4.   

    一般是Response.ContentType设置得不正确,或是没设置时会出现楼主说的这种情况。改为:Response.ContentType = "image/bmp";或其它格式。
      

  5.   

    新建ShowFile.aspx用来显示数据库中的图片,在Page_Load事件中根据查询字符串,实际为数据库中的主键,在数据库中找到相应的记录后读出该image列。
    private void Page_Load(object sender, System.EventArgs e)
    {
    // 在此处放置用户代码以初始化页面
    try
    {
     if(Convert.ToInt32(Request.QueryString["ID"])<=0)
    {
    return;
    }
    }
    catch (Exception )

    return;
    }
    string sql="SELECT * FROM VIDEO  WHERE Video_ID = " + Request.QueryString["ID"] + "";
    SqlConnection connection = new SqlConnection(ConfigurationSettings.AppSettings["conStr"]);
    SqlCommand command = new SqlCommand(sql, connection);
    try
    {
      connection.Open();
      SqlDataReader dr = command.ExecuteReader();
      if(dr.Read())
      {
        Response.Clear();
        Response.AddHeader("Content-Type",dr["Pic_Type"].ToString());
        Response.BinaryWrite((byte[])dr["Video_Pic"]);
       }
       dr.Close();
      connection.Close();
      }
    catch (Exception )

    return;
    }
    }
    =============
    使用的时候,在DataGrid,DataList等膜版列添加IMG控件,然后在其src绑定到上面的ShowFile.aspx中,
    <IMG style="WIDTH: 133px; HEIGHT: 133px" height=133 alt="" onerror=imgErr() src=' <%# "ShowFile.aspx?ID="+DataBinder.Eval(Container.DataItem, "Video_ID") %>' width=133>
    ============
    <SCRIPT language="javascript">
                 function imgErr()
                   { event.srcElement.src='replace.gif';}
    </SCRIPT>
    ===
    onerror=imgErr()用来处理当数据库中图片为空时显示一固定replace.gif,这样页面就要好看些咯哦。