1. 程式人生 > >ASP.NET裡面以二進位制的形式上傳和讀取圖片

ASP.NET裡面以二進位制的形式上傳和讀取圖片

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.IO;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    //上傳圖片
    protected void Button1_Click(object sender, EventArgs e)
    {
        String pathName = this.File1.Value;//獲取檔案路徑
        FileStream fs = new FileStream(pathName, FileMode.Open, FileAccess.Read);//建立檔案流
        byte[] buffByle = new byte[fs.Length];// 建立一個byte 陣列
        fs.Read(buffByle, 0, (int)fs.Length);//讀取流 寫入緩衝區
        fs.Close();
        // 把二進位制存入資料庫
        SqlConnection conn = new SqlConnection("server=PC-200807242100;database=phone;uid=sa;pwd=251");
        SqlCommand comm = new SqlCommand();
        conn.Open();
        comm.CommandText = "insert into image values(@image)";
        comm.Connection = conn;
        comm.CommandType = CommandType.Text;
        comm.Parameters.Add("@image", SqlDbType.Image);//必須是Image 內型
        comm.Parameters[0].Value = buffByle;
        int i=comm.ExecuteNonQuery();
        Response.Write(i);
        conn.Close();
    }
    //讀取圖片
    protected void Button2_Click(object sender, EventArgs e)
    {
        DataTable tb = new DataTable();
        SqlConnection conn = new SqlConnection("server=PC-200807242100;database=phone;uid=sa;pwd=251");
        conn.Open();
        SqlDataAdapter Adapter = new SqlDataAdapter("select * from image ", conn);
        Adapter.Fill(tb);
        byte[] buffByle = (byte[])tb.Rows[0][0];//把資料庫中圖片的二進位制資料轉換一個byte陣列
        int filelength = buffByle.Length;//獲得陣列的長度
        //建立在伺服器上對應虛擬路徑的物理路徑
        string myUrl = HttpContext.Current.Server.MapPath(this.Request.ApplicationPath) + @"/TempDownLoad";
        // 建立檔案流
        FileStream fs = new FileStream(myUrl, FileMode.OpenOrCreate);
        BinaryWriter w = new BinaryWriter(fs);//以二進位制的形式將基元內寫入流
        w.BaseStream.Write(buffByle, 0, filelength);//把資料庫中的圖片二進位制新增到BinaryWriter
        w.Flush();
        w.Close();
        Image1.ImageUrl = Context.Request.ApplicationPath + "/TempDownLoad/";
    }
}