XMLHTTP异步下载文件的时候如何得到下载进度?
如题。
nreadystatechange只在下载完成后得到响应,所以特来求助。
[解决办法]
Dim m_blnStop As Boolean'* -------------------------------------------' 函数说明:基于XMLHTTP的数据下载函数(支持断点续传)' 参数说明:URL待下载的URL' FileName保存下载结果的文件' BlockSize分块大下,根据网络情况而定,以便VB能及时执行DoEvents来获得鼠标和键盘动作并刷新界面' ResumeTransfer是否支持断点续传' 编码:lyserver'* -------------------------------------------Private Sub DownFileByHTTP(ByVal URL As String, FileName As String, Optional BlockSize As Long = 4096, Optional ResumeTransfer As Boolean) Dim xmlHttp As xmlHttp 'Object Dim bytData() As Byte Dim i As Long, fn As Integer, lTotalSize As Long '获得文件长度 Set xmlHttp = CreateObject("MSXML2.XMLHTTP") xmlHttp.open "HEAD", URL, False xmlHttp.send MsgBox xmlHttp.getAllResponseHeaders lTotalSize = xmlHttp.getResponseHeader("Content-Length") Set xmlHttp = Nothing '打开文件 fn = FreeFile() Open FileName For Binary As #fn '判断是否需要断点续传 If ResumeTransfer = True Then i = LOF(fn) Seek fn, i + 1 End If '分块下载数据,并保存到文件中 m_blnStop = False '重置中断标志 Do While i < lTotalSize And m_blnStop = False '没有使用For循环是因为需要下载数与实际下载数可能不一致 '获得文件数据 Set xmlHttp = CreateObject("MSXML2.XMLHTTP") xmlHttp.open "GET", URL, False xmlHttp.setRequestHeader "Referer", Left(URL, InStr(InStr(URL, "//") + 2, URL, "/") - 1) xmlHttp.setRequestHeader "Accept", "*/*" xmlHttp.setRequestHeader "User-Agent", "lyserver" '"Baiduspider+(+http://www.baidu.com/search/spider.htm)" xmlHttp.setRequestHeader "Range", "bytes=" & i & "-" & CStr(i + IIf(lTotalSize - i > BlockSize, BlockSize, lTotalSize - i) - 1) '分段 xmlHttp.setRequestHeader "Content-Type", "application/octet-stream" xmlHttp.setRequestHeader "Pragma", "no-cache" xmlHttp.setRequestHeader "Cache-Control", "no-cache" xmlHttp.send '转换为字节数组 bytData = xmlHttp.responseBody Set xmlHttp = Nothing '保存到文件中 Put fn, , bytData '重置下载开始位置 i = i + UBound(bytData) + 1 '释放控制权 DoEvents '显示进度 Debug.Print "下载完成百分比:" & VBA.FormatPercent(i / lTotalSize) Loop Close fnEnd SubPrivate Sub Command1_Click() '下载,由于在局域网内测试,因此分块设置较大(400K) DownFileByHTTP "http://221.1.222.15:82/down/softwarefb.zip", "c:\2.zip", 20000, True If m_blnStop = True Then MsgBox "数据下载被中断!", vbCritical, "提示" Else MsgBox "数据下载完毕!", vbInformation, "提示" End IfEnd SubPrivate Sub Command2_Click() '中断下载 m_blnStop = TrueEnd Sub
[解决办法]
LS我看你发的几个代码都是复制别人的,来处我都知道,你最近在论坛这么活跃就是为了找人花钱找你接单??
不会直接去猪八戒嘛???都是单啊,看你宣传的个累啊???