[Gambas-user] File Downloading

T Lee Davidson t.lee.davidson at gmail.com
Thu Mar 1 21:32:16 CET 2018


On 02/28/2018 08:10 PM, Shannon Kuchler wrote:
> Total noobie here
> 
> 
> I have searched and searched and can't seem to figure this out
> 
> I simply need to download a file
> 
> 
> The problem is this code works when it feels like it. When it works it works great. When it doesn't work it just creates the
> temp.zip and does nothing.
> 
> It doesn't raise an error so I don't know what's going on.
> 
>  
> 
> On top of that I can't get it to download if the url is redirected
> 
[snip]

HttpClient does not handle redirects automatically. You would need to loop while the response code is 4XX, retrieving the Url in
the response Location header. A recursion depth might be a good idea, since some redirects are circular (probably as bot traps).

Perhaps a more workable solution would be to use, from the Webkit component, Webview and WebDownload. Webview does not have to
be displayed to work. But, it does require a parent so we just create a Form (which we do not open or show) as its container.

The following was actually implemented as a command-line application which seemed to work well:

[code]
' Gambas module file

Private Download As WebDownload

Public Sub Main()

  Dim hForm As Form
  Dim hWebview As WebView

  hForm = New Form As "Form1"
  hWebview = New WebView(hForm) As "Webview1"
  hWebview.Url = "https://github.com/SphereII/SMXBigBackPack/archive/master.zip"
  'First wait for Url to load
  While hWebview.Progress < 1
    Wait 0.1
  Wend
  'Then wait for download to finish
  While Download.Progress < 1
    Print Download.Progress
    Wait 0.1
  Wend
  Select Case Download.Status
    Case WebDownload.Cancelled
      Print "Cancelled"
    Case WebDownload.Error
      Print "Error: " & Download.ErrorText
    Case WebDownload.Finished
      Print "Downloaded " & Download.Size & " bytes."
  End Select

End

Public Sub Webview1_Download(thisDownload As WebDownload)

  ' We shouldn't use Wait in an event handler, so we pass the Download object into the module scope
  Download = thisDownload
  Download.Path = User.home &/ "tmp/master.zip"

End
[/code]


-- 
Lee


More information about the User mailing list