Home / HomePage / Scripts / File Download

File Download


Here's a vbscript function to download a file, given its URL.

It will extract the file's name from the URL, then download that to your %TEMP% folder.
Much thanks to Chrissy of NetNerds, whose script I refactored into this function.

Also, sorry about the syntax highlighting; I used a straight VB highlighter. It's not quite right for vbscript, but better than nothing.

  1. Function DownloadFile(DownloadUrl) 'generic file downloader, saves to temp
  2. 'Get name of file from url (whatever follows the final forwardslash "/")
  3. Dim arURL, FileName, FileSaveLocation
  4. arURL = Split(DownloadUrl,"/",-1,1)
  5. If arURL(UBound(arURL)) = "" Then 'if there is a trailing forwardslash
  6.         FileName = arURL(UBound(arURL) -1)
  7. Else
  8.         filename = arURL(UBound(arURL))
  9. End If
  10. 'Get temp folder location
  11. Dim oFS, TempDir
  12. Set oFS = CreateObject("Scripting.FileSystemObject")
  13. Set TempDir = oFS.getSpecialFolder(2)
  14. FileSaveLocation = TempDir & "\" & FileName
  15.  
  16. ' Fetch the file
  17. Dim oXMLHTTP, oADOStream
  18. Set oXMLHTTP = CreateObject("MSXML2.XMLHTTP")
  19. oXMLHTTP.open "GET", DownloadUrl, false
  20. oXMLHTTP.send()
  21. If oXMLHTTP.Status = 200 Then
  22.         Set oADOStream = CreateObject("ADODB.Stream")
  23.         oADOStream.Open
  24.         oADOStream.Type = 1 'adTypeBinary       
  25.         oADOStream.Write oXMLHTTP.ResponseBody
  26.         oADOStream.Position = 0    'Set the stream position to the start
  27.         If oFS.Fileexists(FileSaveLocation) Then oFS.DeleteFile FileSaveLocation
  28.         Set oFS = Nothing
  29.         oADOStream.SaveToFile FileSaveLocation
  30.         oADOStream.Close
  31.         Set oADOStream = Nothing
  32. End if
  33. Set oXMLHTTP = Nothing
  34. End Function

Post a comment

Your Name or E-mail ID (mandatory)

 



 RSS of this page