Download with Progress bar

From WxPerl Wiki
Jump to: navigation, search

This downloads a file from CPAN and shows a nice Wx::ProgressDialog.

#!/usr/bin/perl

package MyApp;
use base 'Wx::App';
use Wx ':everything';
use LWP::UserAgent;

sub OnInit {
        my( $this ) = @_;

        my $frame = Wx::Frame->new( undef, -1, 'wxPerl', wxDefaultPosition, [ 200, 100 ] );
        $frame->{TXT} = Wx::TextCtrl->new( $frame , -1, '');
        $frame->Show( 1 );
        download( $frame, "http://cpan.org/modules/01modules.index.html" );
}

sub download {
        my( $frame, $from ) = @_;

        my $data = '';
        my $ua = LWP::UserAgent->new();
        my $content_size = $ua->head( $from )->headers()->header('content-length');
        my $pd = Wx::ProgressDialog->new( 'Downloading File', '', $content_size, $frame,
                                        wxPD_AUTO_HIDE | wxPD_APP_MODAL | wxPD_ELAPSED_TIME |
                                        wxPD_ESTIMATED_TIME | wxPD_REMAINING_TIME );
        $ua->get( $from, ':content_cb' => sub { $data.=$_[0]; $pd->Update( length($data) ) } );
        $frame->{TXT}->SetValue( sprintf "Downloaded %d bytes", length($data) );
        $pd->Destroy();
}

MyApp->new()->MainLoop();