VB6下载文件函数代码
VB下载文件模块代码,用着很方便,只需传入网页地址和下载文件名即可,使用的是Scripting.FileSystemObject,已对下载过程中所遇到的各种情况作出处理,异常处理不错。
view source print?
Public Function inteDownloadFile(ByVal sUrl As String, ByVal 01
Filename As String) As String 02 Dim fso, aso, http, Current, Total 03 Dim start, i
04 Dim temp As String, range As String 05 Dim Dnbyte
06 Dnbyte = 20480 '20K 每次下载的字节数n*1024
07 If Not Left(sUrl, 7) = \"http://\" Then sUrl = \"http://\" & sUrl 08 Set fso = CreateObject(\"Scripting.FileSystemObject\") 09 Set aso = CreateObject(\"ADODB.Stream\") 10 Set http = CreateObject(\"Microsoft.XMLHTTP\") 11 If Dir(Filename) <> \"\" Then Kill Filename 12 fso.createtextfile(Filename).Close 13 aso.Type = 1 '数据流类型设为字节' 14 aso.Open
15 aso.loadfromfile Filename '打开文件' 16 start = 0 17 Current = 0 18 Do
19 http.Open \"GET\
http.setrequestheader \"Range\\"bytes=\" & start & \"-\" & 20
CStr(start + Dnbyte) http.setrequestheader \"Content-Type:\\"application/octet-21
stream\" 22 http.Send '构造完数据包就开始发送' 23 For i = 1 To 120 '循环等待'
24 If http.ReadyState = 4 Then Exit For '状态4表示数据接受完
成'
25 Sleep 500 '等待500ms' 26 DoEvents 27 Next
If http.Status = 416 Then mDownLoaddComPlete = True: Exit 28
Do '下载完成 29 If http.Status = 403 Then
30 inteDownloadFile = \"连接数过多\" 31 Exit Do 32 End If
33 If http.Status = 404 Then
34 inteDownloadFile = \"文件无法找到\" 35 Exit Do 36 End If
37 If Not http.ReadyState = 4 Then 38 inteDownloadFile = \"下载文件超时\" 39 Exit Do 40 End If
41 If http.Status > 299 Then
inteDownloadFile = \"未知错误:\" & 42
http.StatusText & \"(\" & http.Status & \")\" 43 Exit Do 44 End If
45 If Not http.Status = 206 Then
46 inteDownloadFile = \"不支持断点续传\" 47 Exit Do 48 End If
49 aso.Position = start '设置文件指针初始位置' 50 aso.write http.responsebody '写入数据'
range = http.getresponseheader(\"Content-Range\") '获得http头51
中的\"Content-Range\"' If range = \"\" Then MsgBox \"无法获取文件大小!\52
\"提示\" '没有它就不知道下载完了没有' temp = Mid(range, InStr(range, \"-\") + 1) 'Content-53
Range是类似123-456/7的样子'
Current = CLng(Left(temp, InStr(temp, \"/\") - 1)) '123是开54
始位置,456是结束位置' Total = CLng(Mid(temp, InStr(temp, \"/\") + 1)) '7是文55
件总字节数' 56 inteDownloadFile = Current & \"/\" & Total
If Total - Current = 1 Then mDownLoaddComPlete = True: Exit 57
Do '结束位置比总大小少1就表示传输完成了' 58 start = start + Dnbyte '继续下载 59 DoEvents 60 Loop While True
61 aso.SaveToFile Filename, 2 '保存文件 62 aso.Close
63 Set aso = Nothing Set fso = Nothing
65 If mDownLoaddComPlete = True Then inteDownloadFile = \"下载完成\" 66 End Function
相关参数:下载文件函数 sUrl 网页地址 FileName 本地文件名