如何將檔案儲存到資料庫中呢,其實並不是想象中那麼難
主要的思路就是將檔案用byte數組儲存,在資料庫中用(blob longblob mediumblob,他們是是一個可以儲存二進位檔案的容器,可以參考百度百科)三者中的任意格式儲存就ok啦!
下面看檔案具體如何寫入資料庫
//eg .string picname = "E:\\BITMAP\\副本.jpg" FileStream fs = new FileStream(picname, FileMode.Open, FileAccess.Read); Byte[] imageByte = new byte[fs.Length]; fs.Read(imageByte, 0, (int)fs.Length); //設定命令參數 MySqlCommand com = new MySqlCommand(); com.CommandText = "update picture set image=@image" + ",image_type='" + imagetype.ToString() + "'" + "where pic_id='" + pic_id + "'"; com.Parameters.Add("@image", MySqlDbType.MediumBlob).Value = imageByte; com.Connection = DB_op.g_conn; return (1==com.ExecuteNonQuery());
讀取檔案:
MySqlDataReader dr = com.ExecuteReader(); if (dr.Read()) //z這。。。。。 { byte[] configByte = (byte[])dr[0]; ////dr.GetBytes(0, 0, configByte, 0, configByte.Length); ////將檔案位元組數組加入到緩衝流 //MemoryStream configStream = new MemoryStream(configByte); ////StreamWriter sw = new StreamWriter(configStream); //StreamReader reader = new StreamReader(configStream); //byte[] bytes = new byte[configStream.Length]; FileStream fs = new FileStream(strsavepath, FileMode.Create); int numBytesRead = 0; // int numBytesToRead = (int)configStream.Length; int numBytesToRead = configByte.Length; while (numBytesToRead > 0) { int n = configStream.Read(bytes, numBytesRead, Math.Min(numBytesToRead, int.MaxValue)); if (n <= 0) { break; } fs.Write(bytes, numBytesRead, n); numBytesRead += n; numBytesToRead -= n; }