This is a very powerful hook and should not be used lightly, it makes some rather advanced features such as upload progress bars possible
#!/usr/bin/env perl
#
# Prototype to measure upload progress under mojolicious.
#
# Instructions to test
# dd if=/dev/zero of=/tmp/file count=1 bs=4MiB #Generate a 4mb upload file
# hypnotoad ./myapp.pl #Run hypnotoad
# curl --limit-rate 1M -F file=@/tmp/file http://localhost:8080/ #Simulate form upload
use Mojolicious::Lite;
app->hook(after_build_tx => sub {
my ($tx, $app) = @_;
$tx->req->on(progress => sub{
my $message = shift;
return unless my $len = $message->headers->content_length;
my $size = $message->content->progress;
say 'Progress: ', $size == $len ? 100 : int($size / ($len / 100)), '%', " size: $size";
})
});
post '/' => sub {
my $self = shift;
$self->render('index')
};
app->start;
__DATA__
@@ index.html.ep
% layout 'default';
% title 'Welcome';
Welcome to the Mojolicious real-time web framework!
Note: This does not work when Mojo is running on PSGI. This is due to the fact that the PSGI layer handles the upload and then passes the request onto Mojo. I have successfully tested with Morbo and Hypnotoad.
Does anyone think it would be beneficial to clean the example up a bit and put it into the documentation somewhere? (The cookbook maybe?)
Cheers,
Adam MacLeod