Option Explicit
Dim mintFile As Integer     '文件句柄
Dim mblnBegin As Boolean    '记录是否是第一次取得数据
Dim mlngDownSize As Long    '已下载的文件大小
Dim mlngTotalSize As Long   '文件大小
Private Sub Form_Load()
Winsock1.RemoteHost = "www.buyele.com"
Winsock1.RemotePort = 80
Winsock1.Connect
End SubPrivate Sub Winsock1_Connect()
Dim strCommand As String
Dim strWebPage As String
strWebPage = "http://www.buyele.com/images/logo.gif"
strCommand = "GET " + strWebPage + " HTTP/1.0" + vbCrLf
strCommand = strCommand + "Accept: */*" + vbCrLf
strCommand = strCommand + "Accept: text/html" + vbCrLf
strCommand = strCommand + vbCrLf
Winsock1.SendData strCommand
End SubPrivate Sub Winsock1_DataArrival(ByVal bytesTotal As Long)
Dim bytData() As Byte
    Dim bytDataHeader() As Byte
    Dim strLine As String
    Dim intCrLf As Integer
    Dim nTempFile As Integer
    Dim strTempFile As String
   
    Winsock1.GetData bytData, vbArray + vbByte, bytesTotal '以二进制形式接送数据,这是关键
    
    If mblnBegin = True Then    '如果是首次接收文件
        mblnBegin = False
        
        '取得得到数据中的第一个空行,因为空行前面的是HTTP头,而非文件内容
        intCrLf = InStrB(bytData, ChrB(13) & ChrB(10) & ChrB(13) & ChrB(10))
        
        bytDataHeader = MidB(bytData, 1, intCrLf - 1)
        
        nTempFile = FreeFile
        strTempFile = "c:\tmp85EER69e2534Ee8545sdf8.txt"
        Open strTempFile For Binary Access Write As #nTempFile      '因为是二进制数据,不好处理,所以将它保存为文本文件再处理,不知道有没有更好的方法?
        Put #nTempFile, , bytDataHeader
        Close #nTempFile
        
        Open strTempFile For Input As #nTempFile
        Line Input #nTempFile, strLine
        strLine = Mid(strLine, InStr(strLine, " ") + 1, 3)  '其中的第一行前三个字符就是HTTP应答结果,如果是非200,那就是不成功了。
      
        Do While Left(strLine, 15) <> "Content-Length:" '直到有一行的开头是Content-Length,因为这一行保存了文件的字节数,通过这可以知道要下载的文件的大小
            Line Input #nTempFile, strLine
        Loop
        Close #nTempFile
        Kill strTempFile
        
        mintFile = FreeFile()
        Open "e:\2.gif" For Binary Access Write As #mintFile
        
        mlngTotalSize = Val(Mid(strLine, InStr(strLine, ":") + 1)) + intCrLf + 3    '得到了文件的大小
       
        bytData = MidB(bytData, intCrLf + 4)    '这次得到的数据有一部分是文件内容
        
    End If
    
   Put #mintFile, , bytData       '写入要保存的文件中
    
    mlngDownSize = mlngDownSize + bytesTotal    '改变已下载的文件大小
       
    If mlngDownSize >= mlngTotalSize Then   '判断是否已完成下载
        Close #mintFile         '关闭文件
        Winsock1.Close
        MsgBox "下载完成!", vbInformation
    End If
End Sub