Search code examples
pythonperlrestencodingsandbox

multipart encoded file content in perl


I want to make a POST Request to a REST API service from Perl. As a POST Form parameter, the service expects a multipart encoded file.

use HTTP::Request::Common;
use LWP::UserAgent;

my $file="/path/to/file";
my $REST_URL = "/path/to/REST/service";
my $ua = LWP::UserAgent->new;
my $response= $ua->post($REST_URL, ['file' => $file]);

I wrote the above code. But obviously the REST server could not understand the POST Request as I have only send the file path to the REST service instead of a multipart encoded file content. Could anyone please let me know how can I make a file multipart encoded and send it as POST Request to a REST service which expect a multipart encoded file as a Form Parameter?

As a side note, I actually want to write the equivalent Perl code of the Python code below.

REST_URL = "/path/to/REST/service"
SAMPLE_FILE = "/path/to/file"

with open(SAMPLE_FILE, "rb") as sample:
   multipart_file = {"file": ("temp_file_name", sample)}
   request = requests.post(REST_URL, files=multipart_file)

But, for my limited knowledge of Python, I didn't understand the line multipart_file = {"file": ("temp_file_name", sample)}. Explanation of what this line is exactly doing will help me as well, I think.


Solution

  • As explained in module documentation HTTP::Request::Common

    $ua->post($REST_URL,
      Content_Type => 'form-data',
      Content      => [
        file => [$file]
      ],
    );