天天看点

ASP.NET中存取图片到数据库的示例(C#)

//开发环境:Window 2003、SQLServer2000、.Net 2.0

//开发语言:C#、ASP.Net

//简介:图片预览,数据库中图片存储及读取

//作者:wayne-ivan

//Email:[email protected]

//PreviewAndSave.aspx 页面如下

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="PreviewAndSave.aspx.cs" Inherits="_PreviewAndSave" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

    <title>无标题页</title>

 <script language="javascript" type="text/javascript">

    function preview()

    { 

        var x = document.getElementById("file4"); 

        //var y = document.getElementById("Image1"); 

        var z = document.getElementById("Image2");

        if(!x || !x.value || !z)

            return; 

         var patn = /\.jpg$|\.jpeg$|\.gif$/i; 

         if(patn.test(x.value))

         {  

            //y.src = "file://localhost/" + x.value; 

            z.src = "file://localhost/" + x.value; 

         }

         else

         {  

                alert("您选择的似乎不是图像文件。"); 

          }

    }

 </script>

</head>

<body id="UP_FILEa">

    <form id="form1" runat="server">

    <div>

        &nbsp;<asp:Image ID="Image1" runat="server" Height="174px" Width="159px" />

        <input id="UP_FILE" runat="server" type="file"  onpropertychange="document.all.Image1.src='file:///'+this.value"/>

        <br />

        <asp:Image ID="Image2" runat="server" Height="174px" Width="159px" />

        <input type="file" name="file4" id="file4" οnchange="preview()" /> <br />

        <asp:TextBox ID="txtDescription" runat="server" Visible="False"></asp:TextBox>&nbsp;

        <asp:Label ID="txtMessage" runat="server" Text="Label" Visible="False"></asp:Label>&nbsp;

        <asp:Button ID="BtnSave" runat="server" OnClick="Button1_Click" Text="上传" />

        <asp:Button ID="BtnRead" runat="server" OnClick="Button3_Click" Text="读取" />&nbsp;

        <asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="读取到另一个页面" Visible="False" /> <br/>

        <asp:RadioButtonList ID="RadioButtonList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged">

        </asp:RadioButtonList></div>

    </form>

</body>

</html>

//PreviewAndSave.aspx.cs  如下

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Data.SqlClient;

using System.IO;

public partial class _PreviewAndSave : System.Web.UI.Page

{

    protected Int32 FileLength = 0;

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

            bindRadioList();

        }

    }

    private void bindRadioList()

    {

        DataTable dt = new DataTable();

        string strCon = System.Configuration.ConfigurationSettings.AppSettings["DSN"];

        SqlConnection Con = new SqlConnection(strCon);

        Con.Open();

        SqlDataAdapter da = new SqlDataAdapter("select ImageID from ImageStore", Con);

        da.Fill(dt);

        RadioButtonList1.DataTextField = "ImageID";

        RadioButtonList1.DataValueField = "ImageID";

        RadioButtonList1.DataSource = dt;

        RadioButtonList1.DataBind();

        if (dt.Rows.Count > 0)

            RadioButtonList1.SelectedIndex = 0;

    }

    //保存图片到数据库

    protected void Button1_Click(object sender, EventArgs e)

    {

        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=ghrmsdb;User ID=sa;Pwd=sa;");

                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;  //记录文件类型

                //把其它单表数据记录上传

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

        }

        //Response.Redirect("ReadImage.aspx?id=1");

        bindRadioList();

    }

    protected void Button3_Click(object sender, EventArgs e)

    {

        //int ImgID =  Convert.ToInt32(Request.QueryString["ID"]); //ID为图片ID

        int ImgID = Convert.ToInt32(RadioButtonList1.SelectedValue);

        //建立数据库链接

        string strCon = System.Configuration.ConfigurationSettings.AppSettings["DSN"];

        SqlConnection Con = new SqlConnection(strCon);

        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.ContentType = (string)SqlReader["ImageContentType"];//设定输出文件类型

        string fileName = Server.MapPath(this.Request.ApplicationPath) + "\\" + ImgID + ".jpg";// + "\\1.jpg";

        System.IO.File.WriteAllBytes(fileName, (byte[])SqlReader["ImageData"]);

        this.Image1.ImageUrl = this.Request.ApplicationPath + "/" + ImgID + ".jpg";

        //输出图象文件二进制数制

        //Response.OutputStream.Write((byte[])SqlReader["ImageData"], 0, (int)SqlReader["ImageSize"]);

        //Response.End();

        //也可以保存为图像

        //      FileStream fs = new FileStream(@"C:\aa.BMP", FileMode.OpenOrCreate, FileAccess.Write);

        //      fs.Write((byte[])SqlReader["ImageData"], 0,(int)SqlReader["ImageSize"]);

        //      fs.Close();

        Con.Close();

    }

    protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)

    {

        ReadPicutre();

    }

    //从数据库中读取文件显示出来

    private void ReadPicutre()

    {

        int ImgID = Convert.ToInt32(RadioButtonList1.SelectedValue);

        //建立数据库链接

        string strCon = System.Configuration.ConfigurationSettings.AppSettings["DSN"];

        SqlConnection Con = new SqlConnection(strCon);

        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.ContentType = (string)SqlReader["ImageContentType"];//设定输出文件类型

        //将文件保存到文件夹,然后在读取

        string fileName = Server.MapPath(this.Request.ApplicationPath) + "\\" + ImgID + ".jpg";// + "\\1.jpg";

        System.IO.File.WriteAllBytes(fileName, (byte[])SqlReader["ImageData"]);

        this.Image1.ImageUrl = this.Request.ApplicationPath + "/" + ImgID + ".jpg";

        //输出图象文件二进制数制

        //Response.OutputStream.Write((byte[])SqlReader["ImageData"], 0, (int)SqlReader["ImageSize"]);

        //Response.End();

        //也可以保存为图像

        //      FileStream fs = new FileStream(@"C:\aa.BMP", FileMode.OpenOrCreate, FileAccess.Write);

        //      fs.Write((byte[])SqlReader["ImageData"], 0,(int)SqlReader["ImageSize"]);

        //      fs.Close();

        Con.Close();

    }

    //在新打开的页面显示图片

    protected void Button2_Click(object sender, EventArgs e)

    {

        //得到用户要上传的文件名

        string strFilePathName = UP_FILE.PostedFile.FileName;

        string strFileName = Path.GetFileName(strFilePathName);

        int FileLength = UP_FILE.PostedFile.ContentLength;

        if (FileLength <= 0)

            return;

        try

        {//上传文件

            Byte[] FileByteArray = new Byte[FileLength]; //图象文件临时储存Byte数组

            Stream StreamObject = UP_FILE.PostedFile.InputStream; //建立数据流对像

            //读取图象文件数据,FileByteArray为数据储存体,0为数据指针位置、FileLnegth为数据长度

            StreamObject.Read(FileByteArray, 0, FileLength);

            //建立SQL Server链接

            string strCon = System.Configuration.ConfigurationSettings.AppSettings["DSN"];

            SqlConnection Con = new SqlConnection(strCon);

            // String SqlCmd = "INSERT INTO ImageStore (ImageData, ImageContentType, ImageDescription, ImageSize) VALUES (@Image, @ContentType, @ImageDescription, @ImageSize)";

            String SqlCmd = "INSERT INTO ImageStore (ImageData) VALUES (@Image)";

            SqlCommand CmdObj = new SqlCommand(SqlCmd, Con);

            CmdObj.Parameters.Add("@Image", SqlDbType.Binary, FileLength).Value = FileByteArray;

            CmdObj.Parameters.Add("@ContentType", SqlDbType.VarChar, 50).Value = UP_FILE.PostedFile.ContentType; //记录文件类型

            //把其它单表数据记录上传

            CmdObj.Parameters.Add("@ImageDescription", SqlDbType.VarChar, 200).Value = txtDescription.Text;

            //记录文件长度,读取时使用

            CmdObj.Parameters.Add("@ImageSize", SqlDbType.BigInt, 8).Value = FileLength;

            Con.Open();

            CmdObj.ExecuteNonQuery();

            Con.Close();

            //跳转页面

            Response.Redirect("ReadImage.aspx?id=1");

        }

        catch

        {

        }

    }

}

程序有点乱,希望对你有帮助!