Skip to content

Instantly share code, notes, and snippets.

@Grinnz
Created November 2, 2018 22:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Grinnz/bb31cdff63006c856aead3e3311d0c13 to your computer and use it in GitHub Desktop.
Save Grinnz/bb31cdff63006c856aead3e3311d0c13 to your computer and use it in GitHub Desktop.
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 => 'http://example.com');
# Prepare body
my $asset = Mojo::Asset::File->new(path => $file_path);
$tx->req->headers->content_type('video/x-msvideo');
$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);
};
$tx->req->content->$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