VBScript: Download and Save a Binary File

Update: If you are an iTunes user that needs VBScript, this page won’t help you. Please visit the following two sites for two different solutions: Apple Docs and KeathMilligan.net.

This is an old script I dug up which I call “fileFetch”. It’s a script that downloads a binary file using XMLHTTP and saves it using an ADO stream. This is handy for nightly downloads and will work within SQL Server DTS packages.

' Set your settings
    strFileURL = "http://www.domain.com/file.zip"
    strHDLocation = "D:\file.zip"

' Fetch the file
    Set objXMLHTTP = CreateObject("MSXML2.XMLHTTP")

    objXMLHTTP.open "GET", strFileURL, false
    objXMLHTTP.send()

If objXMLHTTP.Status = 200 Then
Set objADOStream = CreateObject("ADODB.Stream")
objADOStream.Open
objADOStream.Type = 1 'adTypeBinary

objADOStream.Write objXMLHTTP.ResponseBody
objADOStream.Position = 0    'Set the stream position to the start

Set objFSO = Createobject("Scripting.FileSystemObject")
If objFSO.Fileexists(strHDLocation) Then objFSO.DeleteFile strHDLocation
Set objFSO = Nothing

objADOStream.SaveToFile strHDLocation
objADOStream.Close
Set objADOStream = Nothing
End if

Set objXMLHTTP = Nothing
Posted in VBScript
83 comments on “VBScript: Download and Save a Binary File
  1. GF says:

    Why not to use WGET.exe (command line utility), which can be run from VBSCRIPT?

  2. Chrissy says:

    Hey Gf,
    Powershell works too.. or curl.. ;) But I usually try to use objects that are built-in so that there are no additional downloads required.

  3. bob says:

    WHAT THE HELL IS VBSCRIPT AND HOW DO I DOWNLOAD IT BECAUSE I CAN’T GET ITUNES WITH IT.!!!!!!!!!!!!!!!!

  4. Chrissy says:

    lolz. wtf, bobbles.

    VBScript comes with windows.. you save code to a .txt file, rename it to .vbs and double click. It will launch wscript.exe but srsly, it can damage your system if you run crap code. Your problem will unlikely be solved by figuring out what vbscript is, however. so yeah.

  5. coby says:

    hi, just like bob here, we cannot get itunes or quick time to install into our computer to use the iPod…can you please help us out because we are very unsure of what to do,

    coby

  6. Bader says:

    Greate litle script. Made the day for me!!

  7. Genn says:

    I am also having the exact same problems as bob and Coby, but I’m not sure I understand the answer you gave bob. So what do I do to be able to install iTunes? Every time I try, a window pops up saying I have to have VBScript in order to install iTunes. I tried downloading it, but is not working for me. This is VERY frustrating!

  8. Chrissy says:

    iTunes Users,
    I’m sorry but I cannot help you. I don’t use iTunes and I do not have a solution on how vbscript will help you install iTunes. Please go to Apple’s forums or keep searching Google for an answers.

  9. Bob Jeffery says:

    I could not get it to work with the path below, I think it is because I need to pass it a username and pwd. Other than that it is exactly what I am needing.

    Any suggestions on how to pass it user & pwd?

    Thanks!

    http://www.greenecountymo.org/Recorder_FTP/12-26-2006c.zip

  10. Fred Peters says:

    Thanks for kitty info. We also have an 18 year old cat that has recently started using her "alternate voice" at random times during the day. We used to only hear that a bath time, which is so tramatic to her. She makes a sound similar to a developer who's been asked to create some Crystal Reports.

    I chalked up the recent behavior to kitty dementia, but I'll be on the lookout for any seizures.

    Fred

  11. Lisa says:

    can someone please leave detail help on how to get a vb script download or or how to create a script. Like others having problems with itunes

    any help will be greatly appreciated!!!!

  12. David says:

    Nice script! Thanks for sharing.

  13. Sandy says:

    Cool script !!! I love it !
    Thank you very much

  14. Jason says:

    Thank you very much. I am using this to automate the installation of our new A/V to VPN users. It is much quicker to have them download the application using an external web server than through the VPN concentrator. Thank you 1000 times over.

  15. Maverick says:

    Thanks great script

  16. Cheryl says:

    These posts are encouraging – at least there are others out there with similar problems! My Mandy (17 years old) got very lethargic and started circling the walls of the bedroom very suddenly a few weeks ago. Of course, I took her to the vet, but after tests, all the vet could say was that the results were inconclusive, and to try to build her up a bit by force feeding. She did improve a bit, and was less wobbly and lethargic, but one morning she was as bad as ever. That was the point at which I suspected something neurological, simply because her behaviour change was so marked and so sudden, and the tests had turned up nothing. I didn't want to take her back for more tests – the expense, the stress for Mandy, and the vet was mainly talking about checking out things that can't be treated anyway, like FIV. She's already had the tests for infection and kidney function etc. So I've kept her at home, shut in one room so she can't fall over anything. Now, I've actually seen her have seizures, so I know that's part of the problem; she was probably having them all along, but at night or when I was at work. I don't really know what to do. I don't want to put her through a lot of treatment (I've had to medicate her in the past, and it takes so much out of her, because she fights). I have to travel soon, and my regular cat-sitter isn't too confident about looking out for a sick cat. But Mandy doesn't seem unhappy, and I don't want to euthanize her. Still, the seizures must be becoming more frequent, if now I'm seeing them happen, and it doesn't seem like there's much more to do for an elderly cat than to try to keep her comfortable until the end – or to take her one last time to the vet.

  17. Mihai says:

    Well, I tried using the script to download an image file from my test web server and save it to my hdd, but it keeps erroring out with “Safety settings on this computer prohibit saving data on another domain”, although my test web server is on the local machine. I even turned the whole script into an HTA application, to no avail. I’m using IE7. Any suggestions?

  18. swat says:

    To Mihai:
    It has nothing to do with the location of the installed webserver. The safety settings of IE 7 disallow saving the File with the FileSystemObject (otherwise websites could access your local filesystem >.<). Just click with the right mousebutton on the message and click on allow.

  19. Chrissy says:

    Charles,
    Huh?

    Chrissy

  20. Charles says:

    WGET – damn linux trolls. Because stringing all the things you might want to do in addition to the download into a command line is just backwards.

  21. Casey says:

    You are awesome! Thank you, thank you, thank you!

  22. Gabe says:

    Thanks for the script Works great..

    What if i want to grab an entire folder?

    Thanks

    Gbae

  23. TentHead says:

    Is there any way to monitor the download progress??

  24. CC says:

    Sweet ass script. Thanks.

  25. MRIS says:

    Thats a great script. This is a shorter alternative:

    dim ie
    set ie.createobject(“internetexplorer.application”)
    ie.visible=false
    ie.navigateto(“”)
    do while ie.busy=true
    wscript.sleep 60
    loop
    ie.document.execwb(“saveas”,2,)
    ie.quit

  26. Josh says:

    Very useful. Thank you.

  27. mwalstra says:

    Awesome script, this is just what i was needing :)

  28. felipEx says:

    thanks a lot! was very useful for me ;D

    sorry for ask… i’m really interested to know what plugin do you actually use to dynamically load posts with ajax when you get at page’s bottom (‘Loading the next set of posts’)

    sorry for my crappy english, feel free to mailme =P

  29. Sticks says:

    Excellent script – just the job !, thanx for sharing.

  30. Skyesblue says:

    Is it possible to load an http site, locate an href link and click it, acknowledge the dialog save as… box, and indicate the destination directory all through VBScript. It would be so much easier if an FTP site was provided, but it isn’t, so I’m trying to take your script and make it do the additional steps, not even sure it’s possible, ideas, hints, direction will be appreciated. -rm

  31. Bryan Siew says:

    This is sooooo cool! Thx

  32. James says:

    Very useful,

    thank you

  33. Rui says:

    Works quite well!
    And it´s able to download files from a SP site, for instance, and wget.exe can´t do that…

  34. Amit says:

    Thanks for providing this script, it really helped me a lot.

  35. Amit says:

    I have just tested your script and it worked well with small size of file but in case of large file say 500MB it throws following error:
    ADODB.Stream: Out of memory

    Please fix the code and let us know.

    Thank you very much.

  36. Kei says:

    Thats is so POSSIBLE IMPOSSIBLE!
    The text contains VIRUS! Holy moly once i saved as a text the avast pop up and says that it contain virus even that it just a TEXT VBS.

  37. Chrissy says:

    It’s not a virus nor does it contain a virus. A lot of anti virus apps wrongly consider any vbs file a virus. Or maybe it hates FSO. But you can see clearly from the code that it’s just downloading a file. If that’s a virus, then I download hundreds of viruses a day.

  38. quux says:

    Hi there,

    Nice script – thanks!

    I’ve refactored it a bit so that it can be called as a simple function which downloads directly to your temp dir. So now you can:

    Call DownloadFile(“http://imgs.xkcd.com/comics/faust_20.png”)

    And it will download that file to your temp dir. Here is the function:

    Function DownloadFile(DownloadUrl) ‘generic file downloader, saves to temp
    ‘Get name of file from url (whatever follows the final forwardslash “/”)
    Dim arURL, FileName, FileSaveLocation
    arURL = Split(DownloadUrl,”/”,-1,1)
    If arURL(UBound(arURL)) = “” Then ‘if there is a trailing forwardslash
    FileName = arURL(UBound(arURL) -1)
    Else
    filename = arURL(UBound(arURL))
    End If
    ‘Get temp folder location
    Dim oFS, TempDir
    Set oFS = CreateObject(“Scripting.FileSystemObject”)
    Set TempDir = oFS.getSpecialFolder(2)
    Wscript.Echo TempDir & “\” & FileName
    FileSaveLocation = TempDir & “\” & FileName

    ‘ Fetch the file
    Dim oXMLHTTP, oADOStream
    Set oXMLHTTP = CreateObject(“MSXML2.XMLHTTP”)
    oXMLHTTP.open “GET”, DownloadUrl, false
    oXMLHTTP.send()
    If oXMLHTTP.Status = 200 Then
    Set oADOStream = CreateObject(“ADODB.Stream”)
    oADOStream.Open
    oADOStream.Type = 1 ‘adTypeBinary
    oADOStream.Write oXMLHTTP.ResponseBody
    oADOStream.Position = 0 ‘Set the stream position to the start
    If oFS.Fileexists(FileSaveLocation) Then oFS.DeleteFile FileSaveLocation
    Set oFS = Nothing
    oADOStream.SaveToFile FileSaveLocation
    oADOStream.Close
    Set oADOStream = Nothing
    End if
    Set oXMLHTTP = Nothing
    End Function

  39. quux says:

    Something’s up with WP. When I try to post a link to a better-formatted version of the script above, I get redirected to a blank page. Sorry if I just dumped like 20 bogus posts into your approval queue (if you have one).

  40. Dan says:

    Perfect, just what I was looking for.

  41. Otoman says:

    Can we download a file form Website with BAtch file. without using external command or Functions
    Thankx

  42. Bruce says:

    Beautiful – thank you very much.

  43. Chris says:

    Fantastic script, just does what I need.

    By the way, virus alert can be avoided if “Microsoft.XmlHttp” is used instead of “MSXML2.XMLHTTP”.

    Thank you very much!

  44. Catfish says:

    Nice script, quux! Functional and well written. Thanks for posting.

  45. Kranie says:

    Very nice footwork indeed! This was just was I needed for a project at work.

    You see, we need to download multiple files from our Intranetserver when a new user logs into a given machine, so with a few tweaks, I was able to implement this into out logonscript.

    For the sake of professional courtesy, I credited your work in the comment-header of my script, with a link to this site.

  46. jy says:

    How can i save an image from the website? or just save the whole webpage if that’s difficult?

  47. kellogs says:

    May I know how to execute a file instead of saving it?

    Without prompting?

    I am trying to implement a script which user can call a file and execute it

  48. Malo says:

    Thanks Chrissy this snippet of code saved me from some major headaches, works extremely with a bit of modification it will download from SharePoint document libraries using vbs. Very nice thanks again.

    Mal

  49. AyrA says:

    Here a sample script: it allows to download files and to check, if a File is existant on a Server:
    —–
    OPTION EXPLICIT

    CONST strURL = “http://ayra.ch/default.asp”
    CONST strTarget = “U:\Desktop\default.asp”

    IF ExistFile(strUrl) THEN
    CALL DownloadFile(strUrl,strTarget)
    ELSE
    CALL MsgBox(“Datei nicht gefunden”)
    END IF

    SUB DownloadFile(BYVAL URL,BYVAL Target)
    DIM objXMLHTTP
    DIM objADOStream
    DIM objFSO

    SET objXMLHTTP = CreateObject(“MSXML2.XMLHTTP”)

    CALL objXMLHTTP.open(“GET”, URL, FALSE)
    objXMLHTTP.send()

    IF objXMLHTTP.Status < 400 THEN
    SET objADOStream = CreateObject(“ADODB.Stream”)
    objADOStream.Open
    objADOStream.Type = 1 ‘Binär

    objADOStream.Write objXMLHTTP.ResponseBody
    objADOStream.Position = 0 ‘Beginn von Stream

    SET objFSO = Createobject(“Scripting.FileSystemObject”)
    IF objFSO.Fileexists(Target) THEN
    CALL objFSO.DeleteFile(Target)
    END IF
    SET objFSO = NOTHING

    CALL objADOStream.SaveToFile(Target)
    objADOStream.Close
    SET objADOStream = NOTHING
    END IF

    SET objXMLHTTP = NOTHING
    END SUB

    FUNCTION ExistFile(BYVAL URL)
    DIM objXMLHTTP
    DIM objADOStream
    DIM objFSO

    SET objXMLHTTP = CreateObject(“MSXML2.XMLHTTP”)

    CALL objXMLHTTP.open(“HEAD”, URL, FALSE)
    objXMLHTTP.send()

    IF objXMLHTTP.Status < 400 THEN
    ExistFile=TRUE
    ELSE
    ExistFile=FALSE
    END IF
    SET objXMLHTTP = NOTHING
    END FUNCTION
    —–

  50. wp says:

    Thanks, man! this is really what i am looking for. It’s working great at my XP Pro.
    I prefer to put the download file at my desktop, thus I use

    Set shell=CreateObject(“Wscript.shell”)
    strHDLocation = shell.Specialfolders.Item(“Desktop”)&”\file.zip”

    It’s great.
    Will try on vista system.

  51. VC says:

    Will this work with excel files on a web server?

    http://www.abc.def/ghi/jkl/mno.xls. This kind of link prompts to save/open from my browser.

    Thanks,
    Vc.

  52. Ajay says:

    thank you, it saved my huge time.

    thank you so much.

  53. Sam says:

    Malo, how can you tweak this code to download a file from a SharePoint Document Library? Do you have an example you can post here? Thanks!

  54. Sam says:

    Never mind, Malo… I just discovered that all of my frustration has been due to the SharePoint server blocking MDB files for security reasons. GRRRR!!!! I renamed the file to a TXT file instead of an MDB file and uploaded the TXT version to sharepoint. The script worked just fine as is. Thanks for the script!

  55. Seb says:

    is it feasible to add an authentication part into the script if a username & pwd is required?!?
    thanks!

  56. Earl Russell says:

    I am developing a website and need to allow some files to be download by viewers of the website. These files are .XLS (Excel), PDF and ZIP (combinations of XLS and PDF). Iwould like to be able to download them without the usual “Open”, “Save” or “Cancel” dialog.
    I also need to work arount the Server 2003 4mB limit problem.
    Do you have something or would you be willing to develope something for a fee? If so what would you charge?

  57. Fredrik Jansson says:

    Thanx Chrissy!! Saved me som troublish time… You’re the best!!

  58. Fredrik Jansson says:

    I will dedicate this function to you!

    Public Function ChrissyFileFetch(strFileURL, strHDLocation)
    [...your code...]
    End Function

    :)

    See U!

  59. Chrissy says:

    haha thanks, Fredrik!

  60. Chrissy says:

    Hey Earl,
    Sorry, my plate is full currently. :\

    Chrissy

  61. Eric says:

    Great Script. My issue is that I do not have just one file such as file.zip to down load, I need to download several thousand image files on the fly. I have the URL paths and photo names to each in my database already so I need to dynamically populate the script usign T-Sql. I figure I need to use the FOR EACH…NEXT but I am not getting this done correclty

  62. Rakesh says:

    Hello,

    I am trying to download a word document from sharepoint using the URL, but a corrupted file is being downloaded. I have used the same code as given above. Please anyone help me how to download file from sharepoint.

  63. Nice script, Chrissy. Helped solve some problems. Thanks!

    Seb, I added/changed Chrissy’s script to do http Basic Authentication like this.

    key = base64_encode( username & “:” & password )
    xmlhttp.open “GET”, url, False, username, password
    xmlhttp.setRequestHeader “Authorization”, “Basic ” & key
    xmlhttp.send

    where base64_encode is a sub to do base64 encoding.

  64. Amit says:

    Hi All,

    Realy great script, but my question is “How to download files (xls) from web link that require SSO authentication”. Please help me out.

    I tried using the code above, and passed sso id and password, but its downloaded the Login page in excel.

    Please provide some hint, thanks in advance.

    Thanks & Regards
    Amit

  65. cheh says:

    wow, you rule! :D

  66. Max says:

    How to rewrite a file in the destination?

  67. Kavitha says:

    Excellent Script……I am able use it to automate downloading list of PDF files…..from webpages…

  68. Saggy says:

    THANKS A BUNCH CHRISSY.

    THIS IS VERY VERY SIMPLE SCRIPT AND WORKS GREAT.

    YOU ROCK!!!

  69. Jason says:

    Is there a way to download a file in bits and pieces ? I have a file 0.5GB and it continue getting out of memory errors. Is there a way to page files or so ?

  70. Rafael says:

    Thanks a bunch I will try it out!

  71. Anand says:

    Thank you Chrissy..

    It helped me a lot.. :D Keep doing the gud job… ;)

  72. Maurits says:

    Thanks Chrissy and Tom!
    This really helped me too!

  73. Prakash says:

    Very much useful, Thanks a lot… !!

  74. Wolfgang says:

    Thank you very much for this giant tool. It’s the shortest but also the best working solution for my problem to download a xls-file automatically from a SharePoint document library.

  75. John says:

    This is definitely handy for making quick work of basic downloads.

    For those of you looking for something more advanced with authentication etc…check out cURL. Its available as a library or a command line executable and it has options galore.

  76. Hervé says:

    Thank you Chrissy, you made my day ! I was “webside” for years (and so my VB scripting was far far away). Actually I needed to copy just a few icons (always local with VB) for my “clouds shortcuts generator” ! Et si t’es fière d’être Cajun tape dans tes mains ! Parole de Français !

  77. Systemfire says:

    Great script!!!! Thanks….

  78. Rodrigo Motta says:

    obrigado. script perfect!!

  79. Raul says:

    Excelent!!just what i was looking for!! workd great, thanks

  80. Vinayak says:

    Works very well for me . Awesome script !

  81. ununtu_warrior says:

    Cool thanks!

  82. tttt says:

    Good script

  83. Sam says:

    When I try to get the script to download, i keep getting a error that about failed to write to File. Any help is appreciated!

3 Pings/Trackbacks for "VBScript: Download and Save a Binary File"
  1. [...] found this one pasted below. You can run it with cscript and have it [...]

  2. [...] found this one pasted below. You can run it with cscript and have it [...]

Add Comment Register



Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">