如何向
数据库字段中写入
文件? 1 如何向
数据库字段中写入
文件?(EXE,TXT,DOC等等) 2 如果
文件较大,如何
获取写入进度? 3 如何判断
文件写入成功? __________________________________________________________________________ 忘了说了,还有就是如何读取这些
文件 __________________________________________________________________________ 将
文件流转化为二进制数据后写入
数据库,下面是我写的
代码用于读写
图片文件的,你只需要在
数据库中为字段选择varbinary类型就可以实现其他类型的存储了.没整理,有点乱. Dim b() As Byte Dim fs As filestream Dim br As BinaryReader Dim str
sql As String Try fs = New FileStream(finfo.Name,FileMode.Open,FileAccess.Read) ''将选择的图像
文件读入到
文件流 br = New BinaryReader(fs) b = br.ReadBytes(fs.Length) ''将
文件内容放到字节数组 Catch ex As Exception Msg
Box( "在将
文件读入内存时出错: " + ex.Message) End Try br.Close() fs.Close() str
sql = "insert into test(imageName,photo) " str
sql += "values( '' " & finfo.Name & " '',@photo) " ''二进制数据用@标识 Dim
sqlCn As
sqlConnection = New
sqlConnection( "server=dell;database=study;uid=sa;pwd=; ")
sqlCn.Open() Dim myCommand As
sqlCommand = New
sqlCommand(str
sql,
sqlCn) myCommand.Parameters.Clear() myCommand.Parameters.Add( "@photo ",OleDb.OleDbType.Binary) myCommand.Parameters( "@photo ").Value = b myCommand.ExecuteReader() 读取
文件代码如下: Dim str
sql As String str
sql = "select * from test " Dim
sqlCn As
sqlConnection = New
sqlConnection( "server=dell;database=study;uid=sa;pwd=; ") Dim bw As BinaryWriter Dim bufferSize As Integer = 100 ''定义缓冲区长度为100 Dim outbyte() As Byte = New Byte(bufferSize - 1) {} ''定义缓冲区 Dim retval As Long Dim startIndex As Long = 0 Dim dr As
sqlDataReader Dim myCommand As
sqlCommand = New
sqlCommand(str
sql,
sqlCn)
sqlCn.Open() Dim ms As New System.IO.MemoryStream ''定义内存流对象,将
数据库中存储的图像数据先放到内存流中 Try bw = New BinaryWriter(ms) dr = myCommand.ExecuteReader() dr.Read() Text
Box1.Text = dr.GetString(1) startIndex = 0 retval = dr.GetBytes(2,startIndex,outbyte,bufferSize) Do While retval = bufferSize ''循环读取余下的
内容,每次读取buffersize个字节 bw.Write(outbyte) bw.Flush() ''清空缓冲区 startIndex += bufferSize ''移动位置指针 retval = dr.GetBytes(2,bufferSize) Loop Dim image As Image = image.FromStream(ms) Me.Picture
Box1.Image = image ''利用内存流在picture
Box中
生成图像 bw.Write(outbyte,retval) ''写入最后一块数据 bw.Flush() bw.Close() ms.Close() dr.Close() Catch ex As Exception Msg
Box(ex.Message) End Try __________________________________________________________________________ 那如果是其他类型的
文件呢,就不能用picture
Box控件了,那如何读取呢? __________________________________________________________________________ // 读取 int colIndex = DataReader.GetOrdinal( "MyLargeObjectColumnName "); byte[] buffer = new byte[DataReader.GetBytes(colIndex,null,int.MaxValue)]; DataReader.GetBytes(colIndex,buffer,buffer.Length); // 处理 buffer __________________________________________________________________________ 反正读出来全是二进制的,怎么搞随便 __________________________________________________________________________
原文链接:https://www.f2er.com/vb/263992.html