一个使用URLDownloadToFile函数和IBindStatusCallback接口编写的文件下载类,类名称为URLDownFile。在复制以下代码之前,朋友们需要先先下载Edanmo编写的一个名为olelib.tlb的类型库文件,类的具体代码如下:。
Option Explicit Implements IBindStatusCallback Public Event OnProgress(ByVal lMax As Long,ByVal lProgress As Long,ByVal lStatusCode As BINDSTATUS) Public Function DownloadFile(ByVal strURL As String,ByVal strFileName As String) As Boolean Dim lResult As Long lResult = olelib.URLDownloadToFile(Nothing,strURL,strFileName,Me) DownloadFile = (lResult = 0) End Function Private Sub IBindStatusCallback_OnProgress(ByVal lProgress As Long,ByVal lMax As Long,ByVal lStatusCode As BINDSTATUS,ByVal szStatusText As Long) On Error Resume Next If lMax > 0 Then RaiseEvent OnProgress(lMax,lProgress,lStatusCode) End If End Sub Private Sub IBindStatusCallback_OnStartBinding(ByVal dwReserved As Long,ByVal pib As IBinding) End Sub Private Sub IBindStatusCallback_OnStopBinding(ByVal hresult As Long,ByVal szError As Long) End Sub Private Sub IBindStatusCallback_GetBindInfo(grfBINDF As olelib.BINDF,pbindinfo As BINDINFO) End Sub Private Function IBindStatusCallback_GetPriority() As Long End Function Private Sub IBindStatusCallback_OnDataAvailable(ByVal grfBSCF As BSCF,ByVal dwSize As Long,pformatetc As FORMATETC,pStgmed As STGMEDIUM) End Sub Private Sub IBindStatusCallback_OnLowResource(ByVal reserved As Long) End Sub Private Sub IBindStatusCallback_OnObjectAvailable(riid As UUID,ByVal pUnk As IUnknown) End Sub
调用方法,如果要得到进度事件,则可以在Form或Class里写以下语句:
Dim WithEvents objUrlDownFile As URLDownFile Private Sub Form_Load() Set objUrlDownFile = New URLDownFile objUrlDownFile.DownloadFile "http://avatar.profile.csdn.net/3/5/1/1_lyserver.jpg","c:/temp2.jpg" End Sub Private Sub objUrlDownFile_OnProgress(ByVal lMax As Long,ByVal lStatusCode As olelib.BINDSTATUS) Debug.Print lMax,lStatusCode End Sub
如果只是想实现文件下载,则可以使用以下语句:
Sub main() Dim objUrlDownFile As New URLDownFile objUrlDownFile.DownloadFile "http://avatar.profile.csdn.net/3/5/1/1_lyserver.jpg","c:/temp2.jpg" End Sub