哪位高手能提供保存并浏览图片文件的示例代码。
说明:图片文件作为数据库的一个字段保存,字段属性为image,通过一个按钮打开选择图像文件的页面。通过浏览按钮可浏览图片

解决方案 »

  1.   

    在access中用ole字段类型,sql2000中用image字段,我的方法是将整个文件放到字段中,参考代码如下:
    /// <summary>
    /// 将文件从datarow中下载到本地硬盘
    /// </summary>
    /// <param name="p_DataRow">含有文件内容的行</param>
    /// <param name="p_FieldName">存放文件的字段名</param>
    /// <param name="p_FiledName">存放的文件名</param>
    /// <param name="p_FileExt">文件扩展名</param>
    public static bool DownLoadFile(DataRow p_DataRow,string p_FieldName,string p_FileName,string p_FileExt)
    {
    bool bResult=false;
    //首先将文件导出
    if(p_DataRow[p_FieldName]!=DBNull.Value)
    {
    //如果文件名没有扩展名,则加上扩展名
    string filename=p_FileName.Trim();
    if(filename.IndexOf(".")<0)
    filename+=p_FileExt; Byte[] byteBLOBData =  new Byte[0];
    byteBLOBData = (Byte[])p_DataRow[p_FieldName];
    try
    {
    FileStream fs=new FileStream(filename,FileMode.OpenOrCreate);
    fs.Write(byteBLOBData,0,byteBLOBData.Length);
    fs.Close();
    bResult=true;
    }
    catch(Exception ee)
    {
    MessageBox.Show(ee.Message);
    }
    }
    return bResult;
    } /// <summary>
    /// 将本地文件上传到datarow中
    /// </summary>
    /// <param name="p_DataRow">当前行</param>
    /// <param name="p_FieldName">包含文件内容的字段名</param>
    /// <param name="p_FileName">本地文件名</param>
    public static bool UpLoadFile(DataRow p_DataRow,string p_FieldName,string p_FileName)
    {
    bool bResult=false;
    FileInfo fileinfo=new FileInfo(p_FileName);
    if(fileinfo.Exists)
    {
    try
    {
    FileStream fs=new FileStream(p_FileName,FileMode.Open);
    byte [] myData = new Byte [fs.Length ];
    fs.Position = 0;
    fs.Read (myData,0,Convert.ToInt32 (fs.Length ));
    p_DataRow[p_FieldName] = myData;
    fs.Close();//关闭文件
    bResult=true;
    }
    catch
    {
    }
    }
    else
    MessageBox.Show("文件:"+p_FileName+"不存在!");
    return bResult;
    }
      

  2.   

    http://dotnet.aspx.cc/ShowList.aspx?id=1
      

  3.   

    怎样上传图片,把图片保存到sql  server数据库里,有源代码最好。  
    ---------------------------------------------------------------  
     
    先在SQL  Server中建立一个图片存储的数库表,ImageData  Column为图象二进制数据储存字段,ImageContentType  Column为图象文件类型记录字段,ImageDescription  Column为储蓄图象文件说明字段,ImageSize  Column为储存图象文件长度字段,结构如下:  
    CREATE  TABLE  [dbo].[ImageStore]  (  
           [ImageID]  [int]  IDENTITY  (1,  1)  NOT  NULL  ,  
           [ImageData]  [image]  NULL  ,                                                      &nbsp;  
           [ImageContentType]  [varchar]  (50)  COLLATE  Chinese_PRC_CI_AS  NULL  ,  
           [ImageDescription]  [varchar]  (200)  COLLATE  Chinese_PRC_CI_AS  NULL  ,  
           [ImageSize]  [int]  NULL  
    )  ON  [PRIMARY]  TEXTIMAGE_ON  [PRIMARY]  
    */  
     
    //UpLoadImage.aspx程序内容如下:  
    <%@  Page  Inherits="UploadImage.UploadImage"  SRC="UpLoadImage.cs"  Language="C#"%>  
    <HTML><title>上传图片</title>  
    <BODY  bgcolor="#FFFFFF">  
    <FORM  ENCTYPE="multipart/form-data"  RUNAT="server"  ID="Form1">  
    <TABLE  RUNAT="server"  WIDTH="700"  ALIGN="left"  ID="Table1"  cellpadding="0"  cellspacing="0"  border="0">  
    <TR>  
           &nbsp;<TD>上传图片(选择你要上传的图片)</TD>  
    <TD>  
    <INPUT  TYPE="file"  ID="UP_FILE"  RUNAT="server"  STYLE="Width:320"  ACCEPT="text/*"  NAME="UP_FILE">  
    </TD>  
    </TR>  
    <TR>  
           &nbsp;<TD>  
               文件说明(添加上传图片说明,如:作者、出处)  
           &nbsp;</TD>  
    <TD>  
    <asp:TextBox  RUNAT="server"  WIDTH="239"  ID="txtDescription"  MAINTAINSTATE="false"  />  
    </TD>  
    </TR>  
    <TR>  
    <TD>  
    <asp:Label  RUNAT="server"  ID="txtMessage"  FORECOLOR="red"  MAINTAINSTATE="false"  />  
    </TD>  
    <TD>  
    <asp:Button  RUNAT="server"  WIDTH="239"  ONCLICK="Button_Submit"  TEXT="Upload  Image"  />  
    </TD>  
    </TR>  
    </TABLE>  
    </FORM>  
    </BODY>  
    </HTML>  
    //-------------------------------------------------------------------  
    //UpLoadImage.cs程序内容如下:  
    using  System;  
    using  System.Web;  
    using  System.IO;  
    using  System.Data;  
    using  System.Data.SqlClient;  
    using  System.Web.UI;  
    using  System.Web.UI.WebControls;  
    using  System.Web.UI.HtmlControls;  
    namespace  UploadImage  
    {  
    public  class  UploadImage  :  Page  {  
    protected  HtmlInputFile  UP_FILE;                  &nbsp;//HtmlControl、WebControls控件对象  
    protected  TextBox  txtDescription;  
    protected  Label  txtMessage;  
    protected  Int32  FileLength  =  0;                  &nbsp;//记录文件长度变量  
    protected  void  Button_Submit(System.Object  sender,  System.EventArgs  e)  {  
    HttpPostedFile  UpFile  =  UP_FILE.PostedFile;  &nbsp;//HttpPostedFile对象,用于读取图象文件属性  
    FileLength  =  UpFile.ContentLength;          //记录文件长度  
    try  {  
    if  (FileLength  ==  0)  {      //文件长度为零时  
    txtMessage.Text  =  "<b>请你选择你要上传的文件</b>";  
    }  else  {  
    Byte[]  FileByteArray  =  new  Byte[FileLength];      //图象文件临时储存Byte数组  
    Stream  StreamObject  =  UpFile.InputStream;          &nbsp;//建立数据流对像  
    //读取图象文件数据,FileByteArray为数据储存体,0为数据指针位置、FileLnegth为数据长度  
    StreamObject.Read(FileByteArray,0,FileLength);  &nbsp;  
    //建立SQL  Server链接  
    SqlConnection  Con  =  new  SqlConnection("Data  Source=Localhost;Initial  Catalog=testdb;User  ID=sa;Pwd=;");  
    String  SqlCmd  =  "INSERT  INTO  ImageStore  (ImageData,  ImageContentType,  ImageDescription,  ImageSize)  VALUES  (@Image,  @ContentType,  @ImageDescription,  @ImageSize)";  
    SqlCommand  CmdObj  =  new  SqlCommand(SqlCmd,  Con);  
    CmdObj.Parameters.Add("@Image",SqlDbType.Binary,  FileLength).Value  =  FileByteArray;  
    CmdObj.Parameters.Add("@ContentType",  SqlDbType.VarChar,50).Value  =  UpFile.ContentType;  &nbsp;//记录文件类型  
    //把其它单表数据记录上传  
    CmdObj.Parameters.Add("@ImageDescription",  SqlDbType.VarChar,200).Value  =  txtDescription.Text;  
    //记录文件长度,读取时使用  
    CmdObj.Parameters.Add("@ImageSize",  SqlDbType.BigInt,8).Value  =  UpFile.ContentLength;  
    Con.Open();  
    CmdObj.ExecuteNonQuery();  
    Con.Close();  
    txtMessage.Text  =  "<p><b>OK!你已经成功上传你的图片</b>";//提示上传成功  
    }  
    }  catch  (Exception  ex)  {  
    txtMessage.Text  =  ex.Message.ToString();  
    }}}}  
    //----------------------------------------------------------------------  
    //好了,图片已经上传到数据库,现在还要干什么呢?当然是在数据库中读取及显示在Web页中啦,请看以下程序:  
    //ReadImage.aspx程序内容如下:  
    /-----------------------------------------------------------------------  
    <%@  Page  Inherits="ReadImage.MainDisplay"  SRC="ReadImage.cs"%>  
    //----------------------------------------------------------------------  
    //ReadImage.cs程序内容如下:  
    using  System;  
    using  System.Data;  
    using  System.Data.SqlClient;  
    using  System.Web.UI;  
    using  System.Web.UI.WebControls;  
    using  System.Web.UI.HtmlControls;  
    namespace  ReadImage  {  
    public  class  MainDisplay  :  System.Web.UI.Page  {  
    public  void  Page_Load(System.Object  sender,  System.EventArgs  e)  {  
           int  ImgID  =  Convert.ToInt32(Request.QueryString["ImgID"]);  &nbsp;//ImgID为图片ID  
           //建立数据库链接  
           SqlConnection  Con  =  new  SqlConnection("Data  Source=KING;Initial  Catalog=testdb;User  ID=sa;Pwd=;");  
           String  SqlCmd  =  "SELECT  *  FROM  ImageStore  WHERE  ImageID  =  @ImageID";  
           SqlCommand  CmdObj  =  new  SqlCommand(SqlCmd,  Con);  
           CmdObj.Parameters.Add("@ImageID",  SqlDbType.Int).Value  =  ImgID;  
           Con.Open();  
           SqlDataReader  SqlReader  =  CmdObj.ExecuteReader();  
           SqlReader.Read();      &nbsp;  
           Response.ContentType  =  (string)SqlReader["ImageContentType"];//设定输出文件类型  
           //输出图象文件二进制数制  
           Response.OutputStream.Write((byte[])SqlReader["ImageData"],  0,  (int)SqlReader["ImageSize"]);      &nbsp;  
           Response.End();  
           Con.Close();  
           //很简单吧^_^  
    &nbsp;}  
    }  
    }  
    //--------------------------------------------------------------------  
    //最后,我们当然要把它在Web页面显示出来啦  
    //ShowImage.hml  
    <html>  
    <body>  
    这个是从数据库读取出来的图象:<img  src="ReadImage.aspx?ImgID=1">  
    <body>  
    </html>  
    //------------------------------------------------------------------  
    //最后,这程序当然还很多改进之处,希望大家多想想多编编一定可以写出更多的图象上传程序  
    //Good  Luck,engine  
    ---------------------------------------------------------------  
     
    到www.chinabs.net去吧,那里有源代码下载!  
    ---------------------------------------------------------------  
     
    Byte[]  FileByteArray  =  new  Byte[FileLength];  
    就是定义一个长度为FileLength,类型为Byte的数组  
    Dim  FileByetArray(FileLength)  As  Byte  
     
    UP_FILE为file  field的id
      

  4.   

    在以上的代码中,我们需要注意,在页面表单部分,注意加入:ENCTYPE="multipart/form-data",这与一般的表单不同;另外,以下代码用来实现选择文件的输入框:<INPUT TYPE="file" ID="UP_FILE" RUNAT="server" STYLE="Width:320" ACCEPT="text/*" NAME="UP_FILE">。在以上数据提交界面,我们并没有看到任何对于数据库的处理,这就是ASP.NET编程的好处之一,这里使用了Code Behind技术,就是将一些功能模块设计成为一个类,在这个类中实现需要的功能,我们可以看到,页面代码开头的代码:<%@ Page Inherits="UploadSample.Main" SRC="Upload.cs"%>就是继承了上传图像的类,所有我们上传图像需要的处理就在这里实现。该类的源文件如下:namespace UploadSample {
    public class Main : System.Web.UI.Page {
    protected System.Web.UI.HtmlControls.HtmlInputFile UP_FILE;protected System.Web.UI.WebControls.TextBox txtDescription;protected System.Web.UI.WebControls.Label txtMessage;protected System.Int32 FileLength = 0;
    protected void Button_Submit(System.Object sender, System.EventArgs e) {System.Web.HttpPostedFile UpFile = UP_FILE.PostedFile;FileLength = UpFile.ContentLength;
    try {
    if (FileLength == 0) {
    txtMessage.Text = "<b>*请选择上传的文件</b>";
    } else {
    System.Byte[] FileByteArray = new System.Byte[FileLength];System.IO.Stream StreamObject = UpFile.InputStream;StreamObject.Read(FileByteArray,0,FileLength);System.Data.OleDb.OleDbConnection Con = new System.Data.OleDb.OleDbConnection("Provider=SQLOLEDB;Data Source=localhost;" +"Integrated Security=SSPI;Initial Catalog=northwind");System.String SqlCmd = "INSERT INTO Images (Image, ContentType, ImageDescription, ByteSize) VALUES (?, ?, ?, ?)";System.Data.OleDb.OleDbCommand OleDbCmdObj = new System.Data.OleDb.OleDbCommand(SqlCmd, Con);OleDbCmdObj.Parameters.Add("@Image", System.Data.OleDb.OleDbType.Binary, FileLength).Value = FileByteArray;OleDbCmdObj.Parameters.Add("@ContentType", System.Data.OleDb.OleDbType.VarChar,50).Value = UpFile.ContentType;OleDbCmdObj.Parameters.Add("@ImageDescription", System.Data.OleDb.OleDbType.VarChar,100).Value = txtDescription.Text;OleDbCmdObj.Parameters.Add("@ByteSize", System.Data.OleDb.OleDbType.VarChar,100).Value = UpFile.ContentLength;Con.Open();OleDbCmdObj.ExecuteNonQuery();Con.Close();txtMessage.Text = "<p><b>* 图片上传成功!</b>";
    }
    } catch (System.Exception ex) {
    txtMessage.Text = ex.Message.ToString();
    }}}}
      

  5.   

    以上的代码比较简单,我们现在只来仔细研究数据上传到数据库的代码:System.Data.OleDb.OleDbConnection Con = new System.Data.OleDb.OleDbConnection("Provider=SQLOLEDB;Data Source=localhost;" +"Integrated Security=SSPI;Initial Catalog=northwind");System.String SqlCmd = "INSERT INTO Images (Image, ContentType, ImageDescription, ByteSize) VALUES (?, ?, ?, ?)";System.Data.OleDb.OleDbCommand OleDbCmdObj = new System.Data.OleDb.OleDbCommand(SqlCmd, Con);OleDbCmdObj.Parameters.Add("@Image", System.Data.OleDb.OleDbType.Binary, FileLength).Value = FileByteArray;OleDbCmdObj.Parameters.Add("@ContentType", System.Data.OleDb.OleDbType.VarChar,50).Value = UpFile.ContentType;OleDbCmdObj.Parameters.Add("@ImageDescription", System.Data.OleDb.OleDbType.VarChar,100).Value = txtDescription.Text;OleDbCmdObj.Parameters.Add("@ByteSize", System.Data.OleDb.OleDbType.VarChar,100).Value = UpFile.ContentLength;Con.Open();OleDbCmdObj.ExecuteNonQuery();Con.Close();
    以上代码中,首先建立了一个到SQL Server的数据库链接;然后,建立了一个数据插入的OleDbCommand,注意一点,在建立这个OleDbCommand的时候,我们这里没有使用“@”标志而是使用“?”来代替输入变量。另外,对于SQL.NET而言,因为其提供了一个SqlDbType.Image的数据类型,该类型对数据限制大小为:2,147,483,647,相信绝大部分用户不会上传这样大的文件,因此,可以直接使用以下语句:MySqlCmd.Parameters.Add("@Image", SqlDbType.Image).Value = FileByteArray而在OleDb.NET中,是没有这样类型定义的,我们只能使用OleDbType.Binary类型,这样,对于上传的限制就是8000字节,如果上传文件大于该限制,就会出错,因此,在使用OleDb.NET的时候,我们就必须很清楚的设置上传文件的大小,代码如下:OleDbCmdObj.Parameters.Add("@Image", System.Data.OleDb.OleDbType.Binary, FileLength).Value = FileByteArray
      

  6.   

    引用sqlclient(我用oledb出错了)
    页面可以是文件和表单一起提交;------------------------------------------------------------------------
    写入数据库
    ------------------------------------
    HttpPostedFile UpFile = UP_FILE.PostedFile;  //HttpPostedFile对象,用于读取图象文件属性 
    FileLength = UpFile.ContentLength;     //记录文件长度  
    try { 
    if (FileLength == 0) {   //文件长度为零时 
    txtMessage.Text = "<b>请你选择你要上传的文件</b>";  
    } else { 
    Byte[] FileByteArray = new Byte[FileLength];   //图象文件临时储存Byte数组 
    Stream StreamObject = UpFile.InputStream;      //建立数据流对像 
    //读取图象文件数据,FileByteArray为数据储存体,0为数据指针位置、FileLnegth为数据长度 
    StreamObject.Read(FileByteArray,0,FileLength);    
    //建立SQL Server链接 
    SqlConnection Con = new SqlConnection("Data Source=Localhost;Initial Catalog=testdb;User ID=sa;Pwd=;"); 
    String SqlCmd = "INSERT INTO ImageStore (ImageData, ImageContentType) VALUES (@Image, @ContentType)"; 
    SqlCommand CmdObj = new SqlCommand(SqlCmd, Con); 
    CmdObj.Parameters.Add("@Image",SqlDbType.Binary, FileLength).Value = FileByteArray; 
    CmdObj.Parameters.Add("@ContentType", SqlDbType.VarChar,50).Value = UpFile.ContentType;  //记录文件类型 
    //把其它单表数据记录上传 
    Con.Open(); 
    CmdObj.ExecuteNonQuery();  
    Con.Close(); 
    -------------------------------------------------------------------
    从数据库读出
    ------------------------------------
    int ImgID = Convert.ToInt32(Request.QueryString["ImgID"]);  //ImgID为图片ID  
        //建立数据库链接 
        SqlConnection Con = new SqlConnection("Data Source=KING;Initial Catalog=testdb;User ID=sa;Pwd=;"); 
        String SqlCmd = "SELECT * FROM ImageStore WHERE ImageID = @ImageID"; 
        SqlCommand CmdObj = new SqlCommand(SqlCmd, Con); 
        CmdObj.Parameters.Add("@ImageID", SqlDbType.Int).Value = ImgID; 
        Con.Open(); 
        SqlDataReader SqlReader = CmdObj.ExecuteReader(); 
        SqlReader.Read();      
        //输出图象文件二进制数制 
        Response.BinaryWrite((byte[])SqlReader["ImageData"]);      
        Response.End(); 
        Con.Close(); 
      

  7.   

    多些各位的指教,但发的代码请先验证一下,在我这边都不能执行。我想用一个image控件显示图片