一.上傳圖片到資料庫
///<summary>
/// 上傳圖片
/// </summary>
private void UploadFile()
{
    ///得到用戶要上傳的檔案名
    string strFilePathName = loFile.PostedFile.FileName;
    string strFileName = Path.GetFileName(strFilePathName);
    int FileLength = loFile.PostedFile.ContentLength;

    if (FileLength<=0)
        return;

     ///上傳文件
    try
    {
      
        ///圖像檔臨時儲存Byte陣列
        Byte[] FileByteArray = new Byte[FileLength];

        ///建立資料流程對像
        Stream StreamObject = loFile.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)";
        SqlCommand CmdObj = new SqlCommand(SqlCmd, Con);
        CmdObj.Parameters.Add("@Image",SqlDbType.Binary, FileLength).Value = FileByteArray;
        CmdObj.Parameters.Add("@ContentType", SqlDbType.VarChar,50).Value = loFile.PostedFile.ContentType; //記錄檔類型
       
        ///把其他單表資料記錄上傳
        CmdObj.Parameters.Add("@ImageDescription", SqlDbType.VarChar,200).Value = tbDescription.Text;
       
        ///記錄檔長度,讀取時使用
        CmdObj.Parameters.Add("@ImageSize", SqlDbType.BigInt,8).Value = FileLength;
        Con.Open();
        CmdObj.ExecuteNonQuery();
        Con.Close();

        ///跳轉頁面
        Response.Redirect("ShowAll.aspx");
    }
    catch(Exception ex)
    {
        throw ex;
    }
}

二.從資料庫中讀取圖片
///<summary>
/// 顯示圖片
/// </summary>
private void ShowImages()
 {
    ///ID為圖片ID
    int ImgID = Convert.ToInt32(Request.QueryString["ID"]); 
   
    ///建立資料庫連接
    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"];
   
    ///輸出圖像檔二進位數字制
    Response.OutputStream.Write((byte[])SqlReader["ImageData"], 0, (int)SqlReader["ImageSize"]);
    Response.End();

    Con.Close();   
}

原文地址:http://www.cnblogs.com/Terrylee/archive/2005/11/30/287982.html


arrow
arrow
    全站熱搜

    Roger 發表在 痞客邦 留言(0) 人氣()