Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
mojo streaming file upload
use strict;
use warnings;
use Mojo::UserAgent;
use Mojo::Asset::File;
# Build a normal transaction
my $ua = Mojo::UserAgent->new;
my $tx = $ua->build_tx(POST => '');
# Prepare body
my $asset = Mojo::Asset::File->new(path => $file_path);
$tx->req->headers->content_length(my $size = $asset->size);
# Start writing directly with a drain callback
my $drain;
my $start = 0;
$drain = sub {
my $content = shift;
my $chunk = $asset->get_chunk($start);
$start += length $chunk;
$drain = undef unless $start < $size;
$content->write($chunk, $drain);
# Process transaction
$tx = $ua->start($tx);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment