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 = “http://abc.com/results/myfile01.zip”

‘Local drive’s path where you want to save the file
strSaveFileTo = “C:xxxxxxxyyyyyyyyy\xyz.zip”


‘ create a XMLHTTP object

Set oHTTP = CreateObject(“MSXML2.XMLHTTP”)

oHTTP.open “GET”, strFileUrl, False
oHTTP.send

‘create FSO object
Set oFSO = CreateObject(“Scripting.FileSystemObject”)

‘If  strSaveFileTo file already exist, delete
it

If oFSO.FileExists(strSaveFileTo) Then
  oFSO.DeleteFile(strSaveFileTo)
End If

If oHTTP.Status = 200 Then
  Dim oADOStream
  Set oADOStream = CreateObject(“ADODB.Stream”)
  With oADOStream
    .Type = 1
    .Open
    .Write oHTTP.ResponseBody
    .SaveToFile strSaveFileTo
    .Close
  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)

strExtractFileTo=”C:MyFilePath”

‘If tstrExtractFileTo path does not exist on local
drive, create it

Set oFSO = CreateObject(“Scripting.FileSystemObject”)

If NOT oFSO.FolderExists(strExtractFileTo) Then
   oFSO.CreateFolder(strExtractFileTo)
End If

‘Extract the contants of the zip file.

Set oShell = CreateObject(“Shell.Application”)
Set strZIPFiles=oShell.NameSpace(strSaveFileTo).items
oShell.NameSpace(strExtractFileTo).CopyHere(strZIPFiles)

‘release objects
Set oFSO = Nothing
Set oShell = Nothing

1 thought on “How to download a file from a url using vbscript/QTP”

  1. Really interesting article.
    I tried using it (save to local drive). It does save my file to local drive but the file is not the good size (a few ko only) and cannot be read… Any idea ?

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top