-1

I hope to download a file (such as http://www.example.com/my.zip) and rename it (such as rename my.zip to newfile.zip) when I save it to local disk.

I hope to write a code to do it, I don't know if VBScript can do it, or HTML can do it.

BTW, the following code doesn't work.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <title>HTML5 download Attribute Example</title>
</head>

<body>
<a href="https://ams-nl-ping.vultr.com/vultr.com.100MB.bin"
    download="newfile.zip">Download Your Expense Report</a>
</body>
</html>
Cœur
  • 37,241
  • 25
  • 195
  • 267
HelloCW
  • 843
  • 22
  • 125
  • 310

1 Answers1

2

This should work without a HTML file (if that isn't a requirement), have tested it and it produces a 100MB zip file in C:\temp called newfile.zip.

Just remember when you execute the command, do so in an elevated context.

cscript //nologo "myscript.vbs"

Code myscript.vbs

Option Explicit

Const adTypeBinary = 1
Const adSaveCreateOverWrite = 2

Call main()

Sub main()
  Dim url: url = "https://ams-nl-ping.vultr.com/vultr.com.100MB.bin"
  Dim path: path = "c:\temp\newfile.zip"
  Dim resp: resp = downloadFromURL(url)
  If Not IsEmpty(resp) Then
    Call SaveStreamToFile(resp, path)
  Else
    Call WScript.Echo("Failed to download from " & url)
  End If
End Sub

Function downloadFromURL(url)
  Dim http: Set http = CreateObject("MSXML2.XMLHTTP.6.0")
  Dim stream

  Call http.Open("GET", url, False)
  Call http.Send()

  If http.Status = 200 Then
    downloadFromURL = http.responseBody
  Else
    downloadFromURL = Empty
  End If
End Function

Sub SaveStreamToFile(resp, path)
    Dim stream: Set stream = CreateObject("ADODB.Stream")
    With stream
      Call .Open()
      .Type = adTypeBinary
      Call .Write(resp)
      Call .SaveToFile(path, adSaveCreateOverWrite)
      Call .Close()
    End With
End Sub

There are lots of ways this could be improved, at the moment the variables url and path are hardcoded but could be passed in using the WScript.Arguments collection, allowing you to pass the values as parameters of the script on the command line. Could also improve the error handling passing back the StatusText from HTTP request, but will leave this to you.

This is simply a bare bones example, intended to be built on.

user692942
  • 16,398
  • 7
  • 76
  • 175
  • Thanks! but your code doesn't work! I have created the folder c:\temp ,and create the file myscript.vbs on c:\ After I run cscript //nologo "c:\myscript.vbs" on Windows Command prompt, the system display only a Command windows ,just like https://www.dropbox.com/s/cw6vefvizbp6pja/Download.PNG?dl=0 – HelloCW May 10 '17 at 15:08
  • newfile.zip doesn't be created on c:\temp – HelloCW May 10 '17 at 15:10