简体   繁体   中英

Perl upload file using HTTP::Request

I am using an existing framework to automate some apis. This framework uses the HTTP::Request module. I need to write a script to upload a file. I can do this using the HTTP::Request::Common module,but NOT with the Http::Request module. But I need to use Http::Request only to get this done. Below the code snippets:

Using HTTP::Request::Common\\This Works

    $request = POST $uri,
    Content_Type => 'multipart/form-data',
    Content => [
    file => [$file]
    ]
    ;
    my $results=$ua->request($request ) ;

Using HTTP::Request\\This does not work, I get an error missing file

    my $req = HTTP::Request->new("POST", $uri );
    $req->header(Content_Type => "form-data");
    $req->content('file=>$file');
    my $res = $ua->request($req);

Can someone please tell me what I am doing wrong in the above code?

Unfortunately, there's a lot more going on in the POST method than just wrapping the constructor of an HTTP::Request object (see here ). Including at least the following (from a quick scan through the code):

  • modifying the Content-Type header to be multipart/form-data with a random boundary to indcate where the file data starts in the request
  • setting the Content-Disposition header to the appropriate value
  • reading the file in and storing the contents of the file in the request body

I would highly suggest not trying to do all of the above manually but it's difficult to know your exact constraints and why you can't use HTTP::Request::Common .

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