netnerds.net

24Jan/0782

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.

Dirty Code

' 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 by: Chrissy   Filed under: VBScript Leave a comment
Comments (82) Trackbacks (1)
  1. Why not to use WGET.exe (command line utility), which can be run from VBSCRIPT?

  2. 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. WHAT THE HELL IS VBSCRIPT AND HOW DO I DOWNLOAD IT BECAUSE I CAN’T GET ITUNES WITH IT.!!!!!!!!!!!!!!!!

  4. 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. 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. Greate litle script. Made the day for me!!

  7. 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. 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. 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. 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!!!!

  11. Nice script! Thanks for sharing.

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

  13. 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.

  14. Thanks great script

  15. 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?

  16. 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.

  17. Charles,
    Huh?

    Chrissy

  18. 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.

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

  20. Thanks for the script Works great..

    What if i want to grab an entire folder?

    Thanks

    Gbae

  21. Is there any way to monitor the download progress??

  22. Sweet ass script. Thanks.

  23. 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

  24. Very useful. Thank you.

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

  26. 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

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

  28. 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

  29. This is sooooo cool! Thx

  30. Very useful,

    thank you

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

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

  33. 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.

  34. 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.

  35. 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.

  36. 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

  37. 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).

  38. Perfect, just what I was looking for.

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

  40. Beautiful – thank you very much.

  41. 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!

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

  43. 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.

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

  45. 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

  46. 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

  47. 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
    —–

  48. 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.

  49. 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.

  50. thank you, it saved my huge time.

    thank you so much.

  51. 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!

  52. 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!

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

  54. 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?

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

  56. I will dedicate this function to you!

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

    See U!

  57. haha thanks, Fredrik!

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

    Chrissy

  59. 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

  60. actaully I figured it out.

  61. 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.

  62. 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.

  63. 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

  64. How to rewrite a file in the destination?

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

  66. THANKS A BUNCH CHRISSY.

    THIS IS VERY VERY SIMPLE SCRIPT AND WORKS GREAT.

    YOU ROCK!!!

  67. 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 ?

  68. i have lost my vb scrpit of my computer x

  69. Thanks a bunch I will try it out!

  70. Thank you Chrissy..

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

  71. Thanks Chrissy and Tom!
    This really helped me too!

  72. Very much useful, Thanks a lot… !!

  73. 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.

  74. 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.

  75. 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 !

  76. Great script!!!! Thanks….

  77. obrigado. script perfect!!

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

  79. Works very well for me . Awesome script !

  80. Cool thanks!


Leave a comment