Windows Script Host (jscript): how do i download a binary file?

前端 未结 4 643
[愿得一人]
[愿得一人] 2021-02-10 00:45

i\'m trying to automate a file download with Windows Script Host (JScript). i see ADODB.Stream has an Open method whose documentation makes it seem like it should be possible t

4条回答
  •  感动是毒
    2021-02-10 01:07

    You're on the right track.

    You should be using the XMLHTTPRequest Object to communicate with the server. It's sort of like "curl" for Windows Script. Once the data is read from the remote server, you can write it into an ADODB stream and manipulate it within your script. In your case, writing to a file using the FileSystemObject seems like the most logical course of action.

    So your script might look something like this:

    ' Set your settings
    strFileURL = "http://www.domain.com/file.zip"
    strSavePath = "C:\somefolder\"
    
    ' Send an HTTP request for the file
    Set objXMLHTTP = CreateObject("MSXML2.XMLHTTP")
    
    objXMLHTTP.open "GET", strFileURL, false
    objXMLHTTP.send()
    
    ' If the server responds with "OK"...
    If objXMLHTTP.Status = 200 Then
        ' Create a stream object to write downloaded data to
        Set objADOStream = CreateObject("ADODB.Stream")
        objADOStream.Open
        objADOStream.Type = 1 'adTypeBinary
    
        objADOStream.Write objXMLHTTP.ResponseBody
        objADOStream.Position = 0
    
        ' Create an empty file on disk
        Set objFso = Createobject("Scripting.FileSystemObject")
        ' Make sure we don't have any name collision...
        If objFso.Fileexists(strSavePath) Then objFSO.DeleteFile strSavePath
        Set objFso = Nothing
    
        ' Write the stream data to file
        objADOStream.SaveToFile strSavePath
        objADOStream.Close
        Set objADOStream = Nothing
    End if
    
    Set objXMLHTTP = Nothing
    

提交回复
热议问题