Thursday, January 9

How to download a file from a url using vbscript/QTP

Hello Friends!!

In this post, we will see how to download a file from url/internet to your local drive.

' Path of the file you want to download

strFileUrl = ""

'Local drive's path where you want to save the file
strSaveFileTo = "C:\xxxxxxx\yyyyyyyyy\\"

' create a XMLHTTP object

Set oHTTP = CreateObject("MSXML2.XMLHTTP") "GET", strFileUrl, False

'create FSO object
Set oFSO = CreateObject("Scripting.FileSystemObject")

'If  strSaveFileTo file already exist, delete it
If oFSO.FileExists(strSaveFileTo) Then
End If

If oHTTP.Status = 200 Then
  Dim oADOStream
  Set oADOStream = CreateObject("ADODB.Stream")
  With oADOStream
    .Type = 1
    .Write oHTTP.ResponseBody
    .SaveToFile strSaveFileTo
  End With
  set oADOStream = Nothing
End If

If oFSO.FileExists(strSaveFileTo) Then
  Print "File has been downloaded successfully and save to  " & strSaveFileTo
End If

Above code will save any file to your loacal drive at the given path. Now if the file is a ZIP file, you will need to extract it.

Below code will help you to pick any file from local and extract it's content to given folder

'Local drive's path where you want to Extract the file (in case file is a ZIP file)


'If tstrExtractFileTo path does not exist on local drive, create it
Set oFSO = CreateObject("Scripting.FileSystemObject")

If NOT oFSO.FolderExists(strExtractFileTo) Then
End If

'Extract the contants of the zip file.

Set oShell = CreateObject("Shell.Application")
Set strZIPFiles=oShell.NameSpace(strSaveFileTo).items

'release objects
Set oFSO = Nothing
Set oShell = Nothing