简体   繁体   中英

Perl — HTTP::Request::Common — POST file AND array

I'm trying to POST file into a webapp endpoint. The problem is that in the same request I need to include array as a value of one of the parameters.

my $ua = LWP::UserAgent->new();
my $response = $ua->post(
    $baseurl_local . 'create',
    Content_Type => 'form-data',
    Content      => [
    file =>  [$file],
    targetLang => 'french',
]);

works just fine.

However when I try to

my $ua = LWP::UserAgent->new();
my $response = $ua->post(
    $baseurl_local . 'create',
    Content_Type => 'form-data',
    Content      => [
    file =>  [$file],
    targetLang => ['french','spanish],
]);

I get

Can't open file french: No such file or directory at C:/Strawberry/perl/site/lib/HTTP/Request/Common.pm line 154. HTTP::Request::Common::form_data(ARRAY(0x6800698), undef, HTTP::Request=HASH(0x6803a70)) called at C:/Strawberry/perl/site/lib/HTTP/Request/Common.pm line 67

It would seem Perl thinks array ref with languages is a file.

what am I doing wrong?


To expand on the resolution based on Matt's answer: as I forgot to mention originally, the list of languages comes from user input, so I ended up doing something like:

my @languages = (targetLang => 'french', targetLang => 'spanish');
my $ua = LWP::UserAgent->new();
my $response = $ua->post(
    $baseurl_local . 'create',
    Content_Type => 'form-data',
    Content      => [
        file =>  [$file],
        @languages,
]);

From the HTTP::Request::Common docs :

Multivalued form fields can be specified by either repeating the field name or by passing the value as an array reference.

The POST method also supports the multipart/form-data content used for Form-based File Upload as specified in RFC 1867. You trigger this content format by specifying a content type of 'form-data' as one of the request headers. If one of the values in the $form_ref is an array reference, then it is treated as a file part specification...

So, while you could normally specify a multivalued field with an array reference, array references have special significance with multipart/form-data content, and you'll probably have to get around it by repeating the field name:

my $response = $ua->post(
    $baseurl_local . 'create',
    Content_Type => 'form-data',
    Content      => [
        file       => [$file],
        targetLang => 'french',
        targetLang => 'spanish',
    ],
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM