Sql Server 2000 Image数据读取示例

来源:互联网 发布:修改淘宝密码怎么修改 编辑:程序博客网 时间:2024/06/06 01:22

button1 Paramter提交 button2 Sqlreader读取另存为文件

Protected Sub Button1_Click(ByVal sender As ObjectByVal e As System.EventArgs) Handles Button1.Click
        
Dim imgdatastream As Stream = File1.PostedFile.InputStream '上传图片的文件流
        Dim imgdatalen As Integer = File1.PostedFile.ContentLength '文件流的长度
        Dim imgdata(imgdatalen) As Byte '数据缓冲数组
        imgdatastream.Read(imgdata, 0, imgdatalen) '数据缓冲数组加载上传的文件

        
Dim connstr As String = "server=.;database=test;uid=sa;pwd=sa"
        
Dim connection As New SqlConnection(connstr)
        
Dim Command As New SqlCommand("insert into test (img) VALUES (@img)", connection)
        
Dim paramData As New SqlParameter("@img", Data.SqlDbType.Image) '定义参数//主要,上传大文件没测试//

        paramData.Value 
= imgdata
        
Command.Parameters.Add(paramData)
        connection.Open()
        
Command.ExecuteNonQuery()
        connection.Close()
    
End Sub


    
Protected Sub Button2_Click(ByVal sender As ObjectByVal e As System.EventArgs) Handles Button2.Click
        
Dim Conn As SqlConnection = New SqlConnection("server=.;database=test;uid=sa;pwd=sa")
        
Dim logoCMD As SqlCommand = New SqlCommand("select img from test ", Conn)

        
Dim fs As FileStream '输出文件流
        Dim bw As BinaryWriter '输出缓冲数组 

        
Dim bufferSize As Integer = 100 'image读取缓冲块大小
        Dim outbyte(bufferSize - 1As Byte 'image读取缓冲块
        Dim retval As Long 'image读取的数据长度 
        Dim startIndex As Long = 0 'image读取起始索引位置

        Conn.Open()
        
Dim myReader As SqlDataReader = logoCMD.ExecuteReader(System.Data.CommandBehavior.SequentialAccess) '设定读取方式为大容量数据文件

        
Do While myReader.Read()
            
'文件输出对象
            fs = New FileStream("d:" + System.Guid.NewGuid.ToString + ".jpg", FileMode.OpenOrCreate, FileAccess.Write)
            bw 
= New BinaryWriter(fs)

            
'新行重新初始化索引值
            startIndex = 0

            
'读取文件至image读取缓冲块,返回当前的读取长度
            retval = myReader.GetBytes(0, startIndex, outbyte, 0, bufferSize)

            
'如读取长度等于缓冲区大小,循环输出二进制字节
            Do While retval = bufferSize
                bw.Write(outbyte)
                bw.Flush()

                
'控制读取的未知
                startIndex = startIndex + bufferSize
                retval 
= myReader.GetBytes(0, startIndex, outbyte, 0, bufferSize)
            
Loop

            
'如读取长度小于缓冲区大小,说明到达文件末尾,输出
            bw.Write(outbyte)
            bw.Flush()

            
'关闭文件输出对象
            bw.Close()
            fs.Close()
        
Loop

        
'关闭数据库链接
        myReader.Close()
        Conn.Close()
    
End Sub
 
原创粉丝点击