天天看點

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

        {

        }

    }

}

程式有點亂,希望對你有幫助!