Skip to content

Instantly share code, notes, and snippets.

@Logioniz
Created April 24, 2015 19:58
Show Gist options
  • Save Logioniz/7caa2aeb0198031cd353 to your computer and use it in GitHub Desktop.
Save Logioniz/7caa2aeb0198031cd353 to your computer and use it in GitHub Desktop.
UserAgent: send multipart/form-data.
#!/usr/bin/perl
use Mojo::Base -strict;
use Mojo::Util 'encode';
use Mojo::UserAgent;
say Mojo::UserAgent->new->post('http://127.0.0.1:3000/' => form => {
file_name_1 => [
{
# file => '/path/to/file',
content => 'content 1 of file 1',
filename => encode('UTF-8', "Привет.txt"),
# headers below
X => 'header X'
}, {
content => '1' x (256 * 1024 + 1)
},
'content 3 of file 1' # not in uploads
],
file_name_2 => {
content => 'content of file 2'
},
file_name_3 => 'content content of file 3' # not in uploads
})->res->body;
#!/usr/bin/perl
use Mojo::Base -strict;
use Mojolicious::Lite;
no warnings 'utf8';
$ENV{MOJO_LOG_LEVEL} = 'info';
post '/' => sub {
my $c = shift;
_print(file_name_1 => '' => 10);
_print_upload_info($c->req->every_upload('file_name_1'));
_print(file_name_1 => $c->req->param('file_name_1') => 5);
_print(file_name_2 => '' => 10);
_print_upload_info($c->req->upload('file_name_2'));
_print(file_name_3 => $c->req->param('file_name_3') => 5);
$c->rendered(200);
};
sub _print_upload_info {
my $uploads = shift;
for my $upload (ref $uploads eq 'ARRAY' ? @$uploads : $uploads) {
_print(filename => $upload->filename // '');
_print(size => $upload->size);
_print('header X' => $upload->headers->header('X') // '');
my $asset = $upload->asset;
_print(place => $asset->is_file ? 'file' : 'memory');
_print(file_path => $asset->path) if $asset->is_file;
_print(content => $upload->slurp) unless $asset->is_file;
say '';
}
}
sub _print {
my ($key, $value, $offset) = @_;
$offset //= 20;
say sprintf("\%${offset}s: %s", $key, $value);
}
app->start;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment