perlmojolicioushttp-putmojo-useragent

How to PUT a file using Mojo::Useragent?


I am trying to use the PUT method to upload a file using Mojo::UserAgent, the file may be large, instead of passing the file contents as scalar, is there any other way?

This is what I have tried:

use strict;
use warnings;
use Mojo::UserAgent;
use Mojo::Asset::File;


my $ua = Mojo::UserAgent->new;

my $file = $ARGV[0];

die("File not found") unless(-f $file);

my $a_file = Mojo::Asset::File->new(path => $file);

my $tx = $ua->put('https://postman-echo.com/put' => {'X-Test' => '123G'} => $a_file);

print $tx->success;

print "\n\n";

print $tx->result->body;

print "\n\n";

print $tx->req->text;

Solution

  • See build_tx in Mojo::UserAgent and the example commented

    # PUT request with content streamed from file
    

    at tx in Mojo::UserAgent::Transactor.

    my $ua = Mojo::UserAgent->new;
    my $put = $ua->build_tx(PUT => '…' => {'X-Test' => '123G'});
    $put->req->content->asset(Mojo::Asset::File->new(path => $file));
    my $tx = $ua->start($put);