POST a Multipart request in Perl via LWP


Today I wrote good script which called the 3rd party API and for that I need to send a wav file via multipart.
I worte the code in Perl, which read my keyword via (param) and then I call my API and send the file via multipart.

#!/usr/bin/perl
print "Content-type: text/html\n\n";

use HTTP::Request::Common;
use LWP::UserAgent;
use CGI qw(:standard);
use strict;
use warnings;

my $file, $result, $message;
my $filePath = '/srv/www/cgi-bin/files';

$file = $filePath.'/'.$keyword.".wav";

my $ua = LWP::UserAgent->new;
my $req = $ua->request(POST 'http://www.yourURL',
	      Content_Type => 'form-data',
	      Content => [
		foo => "$foo",
		bar => "$bar",
		Upload => ["$file"]
	      ]
);

print "\nRESPONSE -- \n" . $req->as_string;

# Check the outcome of the response
if ($req->is_success) {
    print $req->content;
}
else {
  print "\n in else not success\n";
}

More links to read :
http://www.perlmonks.org/index.pl?node_id=186591
http://search.cpan.org/~gaas/libwww-perl/lib/HTTP/Request/Common.pm

Happy Programming.

3 Comments

  1. TGo
    Posted February 19, 2011 at 5:47 am | Permalink | Reply

    Short and sweet. Very helpful. Thanks!

  2. Posted April 1, 2013 at 12:34 am | Permalink | Reply

    Pointed me to the right place, but CPAN link is old. Try:
    http://search.cpan.org/search?query=http%3A%3Arequest%3A%3Acommon&mode=all

  3. Posted April 2, 2015 at 12:53 pm | Permalink | Reply

    Hi,
    I want to send 2 different files to an API. File-1 contains XML data and File-2 is a MS word document.
    I am using following code:

    my $signedURL = ‘signedURL’;

    my $file = ‘C:\some.docx’;
    my $text = read_file( ‘C:\some.xml’ ) ;

    my $ua = LWP::UserAgent->new;
    my $req = $ua->request(PUT $signedURL,
    Content_Type => ‘form-data’,
    Content => [
    XML => $text,
    Upload => [“$file”]
    ]
    );

    print “\nRESPONSE — \n” . $req->as_string;

    # Check the outcome of the response
    if ($req->is_success) {
    print $req->content;
    }
    else {
    print “\n in else not success\n”;
    }

    It is generating following error:

    Not a SCALAR reference at C:/Dwimperl/perl/vendor/lib/HTTP/Message.pm line 156.
    at C:/Dwimperl/perl/vendor/lib/HTTP/Message.pm line 156
    HTTP::Message::add_content(‘HTTP::Request=HASH(0x34f4f54)’, ‘ARRAY(0x34e
    84bc)’) called at C:/Dwimperl/perl/vendor/lib/HTTP/Request/Common.pm line 108
    HTTP::Request::Common::_simple_req(undef, undef, undef, undef) called at
    C:/Dwimperl/perl/vendor/lib/HTTP/Request/Common.pm line 22
    HTTP::Request::Common::PUT(‘http://api.aspose.com/v1.1/words/executeMail
    Merge?withRegions…’, ‘Content_Type’, ‘form-data’, ‘Content’, ‘ARRAY(0x34e84bc)
    ‘) called at word_multipart2.pl line 50
    Press any key to continue . . .

    Please, guide

Leave a comment