C#+asp.net+sql數據庫完成圖片的保存與讀取

咱們在使用asp.net時常常會用到數據庫對圖片進行保存和讀取,所以筆者對此進行了仔細研究,圖片的保存和讀取有兩種方式:html

一.以圖片的url地址的方式web

在以圖片url地址的方式中,咱們向數據庫中保存的不是圖片自己,而是圖片的地址,讀取圖片的時候也是圖片的地址,根據保存的地址定位到指定的圖片,首先筆者將講解圖片保存到sql數據庫中的實現方法。sql

1.保存圖片數據庫

1)在數據庫的表中定義一個用來保存圖片路徑的字段,類型爲nchar(40),長度按本身要求設置;服務器

2)咱們經過網絡將圖片上傳至服務器,將圖片保存到服務器指定的路徑,所以咱們須要創建一個文件夾「img'專門放置上傳的圖片,而咱們數據庫中將要保存的地址也是這個文件夾的地址;網絡

3)在aspx文件的Form 標記的 enctype 屬性應該設置成 enctype="multipart/form-data",網頁中放置一個web控件 System.Web.UI.WebControls.FileUpload,這個控件是asp.net中專門用於上傳文件的(html中是 Input(file)),控件命名爲‘inputfile’,另外添加一個按鈕button1,點擊按鈕執行代碼:asp.net

//設置保存路徑ide

   string filepath = HttpContext.Current.Server.MapPath("~/img/");
           string filefullname = filepath + inputfile.FileName;
           inputfile.SaveAs(filefullname);
          string connstring = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Data.mdf;Integrated Security=True;User Instance=True";
          SqlConnection con = new SqlConnection(connstring);
          con.Open();
          string cmd = "insert into [user]([username],[password],[imgurl]) values(
'_username','_password','" + filefullname + "')";//保存圖片
          SqlCommand dcmd = new SqlCommand(cmd, con); 
          dcmd.ExecuteNonQuery();
url

這樣咱們就講上傳的圖片保存到了img文件夾中,其url地址保存到了數據庫中。spa

2.讀取圖片

下面是實現從數據庫中讀取圖片地址並在Image控件中顯示出來,咱們只需進行通常的數據庫讀取獲得imgurl字段的值,而後將字段值賦給Image控件的ImageUrl屬性,代碼以下:

cmd="select [imgurl] from [user] where ([username]='_username')";
        dcmd = new SqlCommand(cmd, con);
        SqlDataReader reader = dcmd.ExecuteReader();
        reader.Read();
        string path = reader[0].ToString();
        Image1.ImageUrl = path;
  

這樣咱們就能夠在Image控件中看到該圖片.

二.以二進制圖片的方式

圖片在數據庫中另外一種保存方式就是將圖片變爲二進制方式存入,可是這種方式在讀取並在Image控件中顯示比較麻煩。下面咱們來看實現方法:

1.保存圖片

保存圖片前,咱們須要在數據庫的表中添加p_w_picpath類型的字段,用於存放二進制的圖片

public byte[] AddImg(System.Web.UI.WebControls.FileUpload inputimg, string ImageType, Int32 maxsize)

    {
        Int32 ImageSize;
        String strImageType;
        Stream ImageStream;
        strImageType = inputimg.PostedFile.ContentType;
        if (strImageType != ImageType)
        {
            Response.Write("<script>alert('圖片類型爲'" + strImageType + ")</script>");
        }
        ImageSize = inputimg.PostedFile.ContentLength;
        if (ImageSize > maxsize)
        {
            Response.Write("<script>alert('圖片不得大於'" + maxsize + "k)</script>");
        }
        ImageStream = inputimg.PostedFile.InputStream;
        byte[] ImageContent = new byte[ImageSize];
        int imgstatus = ImageStream.Read(ImageContent, 0, ImageSize);
        return ImageContent;
    }

而後在button點擊事件代碼:

byte[] p_w_picpathContent;
           p_w_picpathContent = AddImg(inputfile, "p_w_picpath/pjpeg", 512000);
           string connstring = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Data.mdf;Integrated Security=True;User Instance=True";
           SqlConnection con = new SqlConnection(connstring);

           con.Open();
           string cmd = "insert into[user]([username],[password],[headimg]) values(‘_username','_password',@p_w_picpath)";

           SqlParameter prm = new SqlParameter("@p_w_picpath", SqlDbType.VarBinary, p_w_picpathContent.Length, ParameterDirection.Input, false,
   0, 0, null, DataRowVersion.Current, p_w_picpathContent);
           SqlCommand dcmd = new SqlCommand(cmd, con);
           dcmd.Parameters.Add(prm);
           dcmd.ExecuteNonQuery();

這樣咱們就將圖片存入了數據庫

2.讀取圖片

可是這種方式在咱們讀取顯示的方式有些不一樣,並不能直接根據url讓Image控件顯示

cmd = "select [headimg] from [user] where ([username]='_username')";
        dcmd = new SqlCommand(cmd, con);
        SqlDataReader reader = dcmd.ExecuteReader();
        reader.Read();
        byte[] img = (byte[])reader[0]; ;
        con.Close();
        Response.BinaryWrite(img);//這樣咱們就將圖片寫入二進制輸出流,在網頁中顯示

但若是咱們像讓其顯示在Image控件,必須將圖片從數據庫中保存到文件夾爲圖片,將圖片url賦值給ImageUrl。

相關文章
相關標籤/搜索