10

Is it possible to provide HTTP multipart response just like multipart request? The scenario is like, I would like to provide a URL which takes a parameter for EmployeeID, and in return the response should consist of employee's photo, latest payslip and information like name, age and address. The receiving end is not a browser, but it will be a program which gets this response and process them later. Any idea on how to do this?

To give more information on my above question, I have to provide a URL to my friend who will programmatically receive the response. For e.g.:

$response = $ua->request($my_url)

My application is supposed to respond with not just data, but also with files! I was being asked to make it to return multipart response.

gre_gor
  • 6,669
  • 9
  • 47
  • 52
Srikanth Vittal
  • 476
  • 7
  • 22

1 Answers1

8

I'm posing my original https://gist.github.com/1391017 as response.

#!/usr/bin/perl
use strict;
use warnings;

use HTTP::Response;

my $response = HTTP::Response->new(
    200, 'OK', [ 'Content-Type' => 'multipart/form-data' ]
);

$response->protocol('HTTP/1.1');
$response->date(time);
$response->server('Foo/1.0');

my $name = HTTP::Message->new([
    'Content-Type'        => 'text/plain; charset=UTF-8',
    'Content-Disposition' => 'form-data; name="name"',
], 'John Doe');

$response->add_part($name);

my $note = HTTP::Message->new([
    'Content-Type'        => 'text/plain; charset=UTF-8',
    'Content-Disposition' => 'form-data; name="note"',
], <<'NOTE');
Resources:
  o http://search.cpan.org/dist/HTTP-Message/lib/HTTP/Message.pm
  o http://search.cpan.org/dist/HTTP-Message/lib/HTTP/Response.pm
  o http://tools.ietf.org/html/rfc2388
  o http://tools.ietf.org/html/rfc2616
NOTE

$response->add_part($note);

my $blob = HTTP::Message->new([
    'Content-Type'        => 'application/octet-stream',
    'Content-Disposition' => 'form-data; name="blob"; filename="blob.bin"',
]);
$blob->add_content('a chunk');
$blob->add_content(' of data');

$response->add_part($blob);

print $response->as_string;

Output:

HTTP/1.1 200 OK
Date: Thu, 24 Nov 2011 10:03:25 GMT
Server: Foo/1.0
Content-Type: multipart/form-data; boundary=xYzZY

--xYzZY
Content-Type: text/plain; charset=UTF-8
Content-Disposition: form-data; name="name"

John Doe
--xYzZY
Content-Type: text/plain; charset=UTF-8
Content-Disposition: form-data; name="note"

Resources:
  o http://search.cpan.org/dist/HTTP-Message/lib/HTTP/Message.pm
  o http://search.cpan.org/dist/HTTP-Message/lib/HTTP/Response.pm
  o http://tools.ietf.org/html/rfc2388
  o http://tools.ietf.org/html/rfc2616

--xYzZY
Content-Type: application/octet-stream
Content-Disposition: form-data; name="blob"; filename="blob.bin"

a chunk of data
--xYzZY--
chansen
  • 2,446
  • 15
  • 20