你搜索一下csdn,这里有n多这中程序。

解决方案 »

  1.   

    表结构
    ID  Integer  主键ID  
    IMGTITLE  Varchar(50)  图片的标题  
    IMGTYPE  Varchar(50) 图片类型. ASP.NET要以辨认的类型 
    IMGDATA Image 用于存储二进制数据  
    ==========================================
    存入数据库
    ==========================================
    Stream imgdatastream = File1.PostedFile.InputStream;
    int imgdatalen = File1.PostedFile.ContentLength;
    string imgtype = File1.PostedFile.ContentType;
    string imgtitle = TextBox1.Text;
    byte[] imgdata = new byte[imgdatalen];
    int n = imgdatastream.Read(imgdata,0,imgdatalen);
    string connstr=((NameValueCollection)Context.GetConfig("appSettings"))["connstr"];SqlConnection connection = new SqlConnection(connstr);SqlCommand command = new SqlCommand
             ("INSERT INTO ImageStore(imgtitle,imgtype,imgdata)
             VALUES ( @imgtitle, @imgtype,@imgdata )", connection );SqlParameter paramTitle = new SqlParameter
             ("@imgtitle", SqlDbType.VarChar,50 );paramTitle.Value = imgtitle;
    command.Parameters.Add( paramTitle);SqlParameter paramData = new SqlParameter( "@imgdata", SqlDbType.Image );
    paramData.Value = imgdata;
    command.Parameters.Add( paramData );SqlParameter paramType = new SqlParameter( "@imgtype", SqlDbType.VarChar,50 );
    paramType.Value = imgtype;
    command.Parameters.Add( paramType );connection.Open();
    int numRowsAffected = command.ExecuteNonQuery();
    connection.Close();
    =======================================
    读取显示
    =======================================
    private void Page_Load(object sender, System.EventArgs e)
    {
     string imgid =Request.QueryString["imgid"];
     string connstr=((NameValueCollection)
     Context.GetConfig("appSettings"))["connstr"];
     string sql="SELECT imgdata, imgtype FROM ImageStore WHERE id = " + imgid;
     SqlConnection connection = new SqlConnection(connstr);
     SqlCommand command = new SqlCommand(sql, connection);
     connection.Open();
     SqlDataReader dr = command.ExecuteReader();
     if(dr.Read())
     {
      Response.ContentType = dr["imgtype"].ToString();
      Response.BinaryWrite( (byte[]) dr["imgdata"] );
     }
     connection.Close();
    }
      

  2.   

    在ASP.NET中把图片保存到SQL SERVER数据库
    翻译:吕绍伟介绍
    在很多情况下,我们需要把图片保存到数据库中。在某些应用程序中,存在一些敏感信息不能被存储到文件系统中,因为存储在文件系统上的任何图片都很容易被用户非法获得。本文将讨论在ASP.NET中怎样把图片保存到SQL SERVER数据库中。在本文中我们将了解到以下几方面的内容:l         上载图片文件的要求l         使用Strem对象l         获得上载图片大小和类型l         如何使用InputStream方法?上载图片文件的要求在开始上载前我们需要作两件重要的事情#Form标记的enctype属性需要被设置为如下形式:enctype="multipart/form-data" #提供一个让用户选择图片文件的Html控件:<input type=file> #还要引用System.IO命名空间来处理Strem对象上述的三项都要应用到aspx页中。在SQL SERVER中还有以下的一些要求:#一个至少有一个字段类型为Image的表#另外有一个用来存储图片类型的Varchar类型的字段就更好了那么,我们有了一个有Image字段类型的数据表和一个<input type=file>(HTML文件控件)。我们还需要一个提交按钮,当用户选择好图片后可以点击它。在按钮的OnClick事件中我们要获得图片文件的内容并最终把它插入到数据表中。让我们来看看按钮的OnClick事件,它读取图片并把图片插入到数据表中。提交按钮的OnClick事件代码   Dim intImageSize As Int64
        Dim strImageType As String
        Dim ImageStream As Stream    ' Gets the Size of the Image
        intImageSize = PersonImage.PostedFile.ContentLength    ' Gets the Image Type
        strImageType = PersonImage.PostedFile.ContentType    ' Reads the Image
        ImageStream = PersonImage.PostedFile.InputStream    Dim ImageContent(intImageSize) As Byte
        Dim intStatus As Integer
        intStatus = ImageStream.Read(ImageContent, 0, intImageSize)    ' Create Instance of Connection and Command Object
        Dim myConnection As New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
        Dim myCommand As New SqlCommand("sp_person_isp", myConnection)    ' Mark the Command as a SPROC
        myCommand.CommandType = CommandType.StoredProcedure    ' Add Parameters to SPROC
        Dim prmPersonImage As New SqlParameter("@PersonImage", SqlDbType.Image)
        prmPersonImage.Value = ImageContent
        myCommand.Parameters.Add(prmPersonImage)    Dim prmPersonImageType As New SqlParameter("@PersonImageType", SqlDbType.VarChar, 255)
        prmPersonImageType.Value = strImageType
        myCommand.Parameters.Add(prmPersonImageType)    Try
            myConnection.Open()
            myCommand.ExecuteNonQuery()
            myConnection.Close()
            Response.Write("New person successfully added!")
        Catch SQLexc As SqlException
            Response.Write("Insert Failed. Error Details are: " & SQLexc.ToString())
        End Try  它是如何工作的?对象PersonImage 是HTMLInputFile 控件。首先我们要获得被插入图片的大小,通过如下方法实现:intImageSize = PersonImage.PostedFile.ContentLength 接着要通过ContenType属性获得图片类型。最后最重要的是要获得图片文件流,通过如下方法实现:ImageStream = PersonImage.PostedFile.InputStream 我们有一个byte数组ImageContent,准备用来保存图片内容。整个图片通过Stream对象的Read方法读取,这个方法有三个参数,即:#被复制的图片内容的目标位置#读的开始位置#需要被读的子节数读声明如下:intStatus = ImageStream.Read(ImageContent, 0, intImageSize) 现在,我们读取了整个图片内容。接着我们需要把图片内容插入SQL数据表中,我们将用用一个存储过程把图片类型和图片插入SQL数据表。如果你看过上面的代码清单,你就知道我们把数据类型设置为SqlDbType.Image.就这样,我们成功地把图片保存到了SQL SERVER数据库。例子的输出样例
      

  3.   

    to wxlada(绿茶) :
    首先感谢回帖。可是,您这个读出来是一个二进制文件吧,而我想要得是一个图片并显示出来,而且不能直接上传到数据库。to MasterLRC(但丁):
    vb的东西看不懂啊~
      

  4.   

    最简单的就是上传文件保存在服务器硬盘,文件信息保存在数据库
    给你例子看看:  
    注: 有些类你没有,可以暂时不使用,但不影响上传功能
    //page : upload.aspx <%@ Page language="c#" Codebehind="upload.aspx.cs" AutoEventWireup="false" Inherits="RiseGuide.MegaNet.admin.upload" %>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
    <HTML>
    <HEAD>
    <title>upload</title>
    <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
    <meta name="CODE_LANGUAGE" Content="C#">
    <meta name="vs_defaultClientScript" content="JavaScript">
    <LINK href="../cmdjs/wgnet_style.css" type="text/css" rel="stylesheet">
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
    <script id="clientEventHandlersJS" language="javascript">
    <!--
    var i;
    function File_onblur(e) {
    try{
    i=e.name.replace("File","");
    var path=document.all["File"+i.toString()].value;
    document.all["Text"+i.toString()].value=getname(path);
    }catch(e){
    }
    }
    function getname(path){
    var f1;
    var name;
    f1=path.split("\\");
    name=f1[f1.length-1];

    return name;
    }function Text_onfocus(e) {
    try{
    i=e.name.replace("Text","");
    var path=document.all["File"+i.toString()].value;
    if(document.all["Text"+i.toString()].value=="") 
    document.all["Text"+i.toString()].value=getname(path);
    }catch(e){
    }
    }//-->
    </script>
    </HEAD>
    <body>
    <FORM id="Form1" method="post" encType="multipart/form-data" runat="server">
    <FONT face="宋体">&nbsp; 文件上传系统&nbsp;&nbsp;
    <asp:TextBox id="TextBox1" runat="server" Width="24px" ToolTip="改变文本框的值可以增加上传文件个数.." MaxLength="2"
    AutoPostBack="True">1</asp:TextBox>&nbsp;上传文件个数&nbsp;
    <TABLE id="TableMain" height="82" cellSpacing="0" cellPadding="4" width="500" border="1"
    runat="server" style="BORDER-COLLAPSE: collapse">
    <TR>
    <TD width="203" height="28">文件名称(默认为文件名)</TD>
    <TD height="28">选择上传的文件</TD>
    </TR>
    <TR>
    <TD align="right" colSpan="2">&nbsp;
    <asp:Button id="Button1" runat="server" Text=" 保存 " Width="72px"></asp:Button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    </TD>
    </TR>
    </TABLE>
    </FONT>
    <asp:Label id="Label1" runat="server" Width="500px">注意:文件总大小不能超过4M..</asp:Label>
    </FORM>
    </body>
    </HTML>
    //page: unload.aspx.csusing 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 RiseGuideClassLibrary;namespace RiseGuide.MegaNet.admin
    {
    /// <summary>
    /// upload 的摘要说明。
    /// </summary>
    public class upload : System.Web.UI.Page
    {
    protected System.Web.UI.WebControls.Button Button1;
    protected System.Web.UI.WebControls.Label Label1;
    protected System.Web.UI.WebControls.TextBox TextBox1;
    protected System.Web.UI.HtmlControls.HtmlTable TableMain;
    int FileCount=1;
    private void Page_Load(object sender, System.EventArgs e)
    { Response.Clear();
    this.Label1.Text ="提示:上传文件大小总和不能超过4M..";
    try
    {
    FileCount=Int32.Parse(this.TextBox1.Text);
    }
    catch
    {
    this.TextBox1.Text="1";
    FileCount=1;
    }
    if(!IsPostBack)
    {
    CreateInputFile();
    }
    } #region Web 窗体设计器生成的代码
    override protected void OnInit(EventArgs e)
    {
    //
    // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
    //
    InitializeComponent();
    base.OnInit(e);
    }

    /// <summary>
    /// 设计器支持所需的方法 - 不要使用代码编辑器修改
    /// 此方法的内容。
    /// </summary>
    private void InitializeComponent()
    {    
    this.TextBox1.TextChanged += new System.EventHandler(this.TextBox1_TextChanged);
    this.Button1.Click += new System.EventHandler(this.Button1_Click);
    this.Load += new System.EventHandler(this.Page_Load); }
    #endregion /// <summary>
    /// 创建文件选择框
    /// </summary>
    private void CreateInputFile()
    {
    while(TableMain.Rows.Count >2) 
    {
    TableMain.Rows.RemoveAt(TableMain.Rows.Count-1);//清除代码产生的行
    } for(int i=0;i<FileCount;i++)
    {
    int pos=TableMain.Rows.Count-1;  //倒数第二行
    HtmlTableRow row=new HtmlTableRow();
    HtmlTableCell cell1=new HtmlTableCell();
    HtmlInputText txt=new HtmlInputText();
    txt.ID = "Text"+(i+1).ToString();
    txt.Attributes["onfocus"]="javascript:Text_onfocus(this)";

    cell1.Controls.Add(txt);
    HtmlTableCell cell2=new HtmlTableCell();
    HtmlInputFile file=new HtmlInputFile();
    file.ID=  "File"+(i+1).ToString();
    txt.Attributes["onblur"]="javascript:File_onblur(this)";

    cell2.Controls.Add(file);
    row.Cells.Add(cell1);
    row.Cells.Add(cell2);

    //插入生成的行
    this.TableMain.Rows.Insert(pos,row);
    }
    //this.Label1.Text ="提示:当前创建了"+this.TextBox1.Text+"个文件上传框";
    } private void Button1_Click(object sender, System.EventArgs e)
    {
        HttpFileCollection f=Request.Files;
    this.Label1.Text ="提示:";
    if(Request.TotalBytes>4096000)  //判断输入大小
    {
    this.Label1.Text ="提示:上传文件内容总和大于了4M,请重新选择文件";
    CreateInputFile();
    return ;
    }

    for(int i=0;i<f.Count ;i++)
    {
    if(Request.Form["File"+(i+1).ToString()]=="")
    continue;
    if(f[i].FileName =="") 
    {
    this.Label1.Text ="提示:请选择您要上传的文件";
    continue;
    } string name="";
    try
    {
    string[] names=f[i].FileName.Split('\\');
    name=names[names.Length-1];
    f[i].SaveAs(Server.MapPath("../photo")+"\\"+name);
    if(Request.Form["Text"+(i+1).ToString()]=="")
    SysPhoto(name.Split('.')[0]+DateTime.Now.ToString(),name);
    else
    SysPhoto(Request.Form["Text"+(i+1).ToString()],name);

    this.Label1.Text += f[i].FileName +" 上传 成功..<BR>"; }
    #if DEBUG
    catch(Exception err)
    {
    this.Label1.Text += f[i].FileName +" 上传 失败.."+err.Message+"<BR>";
    }
    #else
    catch
    {
    this.Label1.Text += f[i].FileName +" 上传 失败..<BR>";
    }
    #endif
    }
    CreateInputFile();
    } private void TextBox1_TextChanged(object sender, System.EventArgs e)
    {
    CreateInputFile();
    } /// <summary>
    /// 保存到数据库
    /// </summary>
    private void SysPhoto(string name,string url)
    {
    dataBase db=new dataBase();
    db.ExecuteSql("insert into Sysphoto (name,url) values ('"+name+"','"+url+"')");
    }
    }
    }
     使用就直接取得地址就可以了
      

  5.   

    有这么负责吗?
    你可以把图片放到数据库中。
    你也可以把图片放在硬盘上阿!数据库存一路径就可以了.
    using System.io简单的很