Wednesday, October 14, 2009

Binary HTTP Download

Accessing files via vbscript is easy enough using the FileSystemObject.  You probably already know how to create the object, get a file, copy it, delete it, and lots of other cool things.  But what if the file isn't on the local machine or server?  What if the file is on a web server?  You certainly can't access it like a machine on your local intranet. 

Does that mean you can't access those files?  Using the routine below you can.  Here's the scenario that prompted this code.  I was writing an application in HTA that needed to reference a file on the web that is updated quite frequently.  I could have copied it to a local server and used FSO to access it but that means more administrative overhead for me.  If the application had HTTP access, why not let it download the file?  After some research it turns out you can use the MSXML object to download files directly to your computer.  Check it out:

Sub httpBinaryDownload(sstrURL2,sstrPath2)
 
        Set sobjFSO = Createobject("Scripting.FileSystemObject")
 
        sarrURL = Split(sstrURL2,"/")
        sstrFile = sarrURL(UBound(sarrURL))
        
        sstrFullPath = sstrPath2 & "\" & sstrFile
        
        Set sobjXMLHTTP = CreateObject("MSXML2.XMLHTTP")
     
        sobjXMLHTTP.open "GET", sstrURL2, False
        sobjXMLHTTP.send()
     
        If sobjXMLHTTP.Status = 200 Then
          Set sobjADOStream = CreateObject("ADODB.Stream")
          sobjADOStream.Open
          sobjADOStream.Type = 1 'adTypeBinary
     
          sobjADOStream.Write sobjXMLHTTP.ResponseBody
          sobjADOStream.Position = 0    'Set the stream position to the start
     
            If sobjFSO.Fileexists(sstrFullPath) Then sobjFSO.DeleteFile sstrFullPath
          Set sobjFSO = Nothing
     
          sobjADOStream.SaveToFile sstrFullPath
          sobjADOStream.Close
          Set sobjADOStream = Nothing
        End If
     
        Set sobjXMLHTTP = Nothing
 
 
    End Sub  

Note: If you are copying and pasting, be sure to fix the line breaks.

Now, this code takes in the http path of the file and the local folder path to save the file to.  It makes an MSXML object and ADODB stream to save the file locally.  It works fairly fast!  Test it out and if you run into trouble, let me know.

-Corey Thomas

No comments: