UtterAccess HomeUtterAccess Wiki

Welcome Guest ( Log In | Register )

Custom Search
Edit Discussion
> DownloadBinary    

The following code uses the MSXML HTTPRequest class to download a binary file from the internet. You can apply a timeout (defaults to 45 seconds), and optionally you can pass a string byref to return the Header information from the request.

Example Usage:
DownloadBinary "http://SomePage.com/SomeFile.xlsx", "C:\MyDownloadedFile.xlsx"


' DownloadBinary
' http://www.utteraccess.com/wiki/index.php/DownloadBinary
' Code courtesy of UtterAccess Wiki
' Licensed under Creative Commons License
' http://creativecommons.org/licenses/by-sa/3.0/
' You are free to use this code in any application,
' provided this notice is left unchanged.
' rev  date                          brief descripton
' 1.0  2012-01-17                    
Public Function DownloadBinary( _
   src As String, _
   dest As String, _
   Optional TimeoutMS As Long = 45000, _
   Optional ByRef Header As String _
   ) As Long
 'Currently provides no validation for src or dest
 'prelim version
 'returns 0 on success
 'returns -1 on timeout
 'returns httpRequestStatus on other errors
 Dim req As Object
 Dim lTimer As Long
 Dim bFlag As Boolean
 Dim bTimeout As Boolean
 Dim vBytes As Variant
 Dim bBytes() As Byte
 Dim iFile As Integer
 Set req = CreateObject("MSXML2.XMLHTTP.3.0")
 req.Open "GET", src, True
 While bFlag = False
   DoEvents: DoEvents: DoEvents
   If req.readystate <> 4 Then
     'not done
     If lTimer >= TimeoutMS Then
       bFlag = True
       bTimeout = True
     End If
     bFlag = True
   End If
   lTimer = lTimer + HTTPREQ_TIMEOUT_CHECK

 If bTimeout Then
   DownloadBinary = -1 'timeout
   If req.Status = 200 Then
     Header = req.getAllResponseHeaders()
     vBytes = req.responseBody

     ReDim bBytes(0 To UBound(vBytes))
     bBytes = vBytes
     iFile = FreeFile()
     Open dest For Binary Access Write As #iFile
     Put #iFile, , bBytes
     Close #iFile
     DownloadBinary = 0
     DownloadBinary = req.Status
   End If
 End If
 Set req = Nothing
End Function

Creative Commons License
DownloadBinary by UtterAccess Wiki is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
Editing and revision of the content is freely encouraged; for details, see Expected Usage.

Edit Discussion
Custom Search

Thank you for your support!
This page has been accessed 5,910 times.  This page was last modified 10:47, 17 January 2012 by Jack Leach.   Disclaimers