Home » Controls » How to download a file using Inet control with Progress Bar
How to download a file using Inet control with Progress Bar
Posted on August 17, 2009
Here is an sample code to download a file from internet using Inet control with Progress Bar:
Instructions:
a. Open a New VB project
b. Create a new form and name it as frmFileDownload
c. Add an Inet control and name it as InetFileDownload
d. Add a progressbar control and name it as FileDownloadProgress
e. Add a Command button and name it as cmdDownload
f. Open the code window of the form and add the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | Option Explicit Private Sub cmdDownload_Click() Screen.MousePointer = vbHourglass FileDownloadProgress.Value = 0 FileDownloadProgress.Visible = True DownloadFile "http://www.testsite.com/testfile.txt", App.Path & "\testfile.txt" Screen.MousePointer = vbDefault Call MsgBox("Download Completed.", vbInformation, App.Title) FileDownloadProgress.Visible = False End Sub Private Sub Form_Load() FileDownloadProgress.Visible = False End Sub Sub DownloadProgress(intPercent As String) FileDownloadProgress.Value = intPercent End Sub Public Sub DownloadFile(strURL As String, strDestination As String) Const CHUNK_SIZE As Long = 1024 Dim iFile As Integer Dim lBytesReceived As Long Dim lFileLength As Long Dim strHeader As String Dim b() As Byte Dim I As Integer DoEvents With InetFileDownload .URL = strURL .Execute , "GET", , "Range: bytes=" & CStr(lBytesReceived) & "-" & vbCrLf While .StillExecuting DoEvents Wend strHeader = .GetHeader End With strHeader = InetFileDownload.GetHeader("Content-Length") lFileLength = Val(strHeader) DoEvents lBytesReceived = 0 iFile = FreeFile() Open strDestination For Binary Access Write As #iFile Do b = InetFileDownload.GetChunk(CHUNK_SIZE, icByteArray) Put #iFile, , b lBytesReceived = lBytesReceived + UBound(b, 1) + 1 DownloadProgress (Round((lBytesReceived / lFileLength) * 100)) DoEvents Loop While UBound(b, 1) > 0 Close #iFile End Sub |
If you find any issues with the above code please post as a comment.
Enjoy this article?
Filed under: Controls
Leave a comment