如何將文件保存到數據庫中呢,其實並不是想象中那么難
主要的思路就是將文件用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; }
