Mojo::UserAgent下载大文件的时候,如何打印下载进度

利用 Mojo::Message

#!/usr/bin/env perl
use feature qw(say);
use warnings;

use Mojo::UserAgent;

my $url = "https://cpan.metacpan.org/authors/id/S/SR/SRI/Mojolicious-7.30.tar.gz";
my $ua  = Mojo::UserAgent->new();
my $tx  = $ua->build_tx(GET => $url);
$tx->res->on(progress => sub {
    my $msg = shift;
    return unless my $len = $msg->headers->content_length;
    my $size = $msg->content->progress;
    say 'Progress: ', $size == $len ? 100 : int($size / ($len / 100)), '%';
});
$ua->start($tx);
say($tx->res->code, ' ', $tx->res->message);

利用 Mojo::Content

#!/usr/bin/env perl

use 5.12.0;
use warnings;

use Mojo::UserAgent;

my $url = "https://cpan.metacpan.org/authors/id/S/SR/SRI/Mojolicious-7.30.tar.gz";
my $ua  = Mojo::UserAgent->new();
my $tx  = $ua->build_tx(GET => $url);

$tx->res->content->on(read => sub {
    my $content = shift;
    return unless my $len = $content->headers->content_length;
    my $size = $content->progress;
    say 'Progress: ', $size == $len ? 100 : int($size / ($len / 100)), '%';
});
$ua->start($tx);

say($tx->res->code, ' ', $tx->res->message);

参考:

  1. http://stackoverflow.com/questions/10086592/mojouseragent-get-with-userdefined-callback
  2. https://metacpan.org/pod/Mojo::UserAgent#build_tx
  3. https://metacpan.org/pod/Mojo::Message#progress
  4. https://metacpan.org/pod/Mojo::Content#read

Perl

这篇文章: 有用 无用
创建 2017-04-16 05:25:46 / 更新 2017-04-16 05:25:46