HTTP multipart response using Perl or PHP

前端 未结 1 672
渐次进展
渐次进展 2021-01-04 22:57

Is it possible to provide HTTP multipart response (using Perl/PHP) just like multipart request? The scenario is like, I would like to provide a URL whick takes a parameter f

相关标签:
1条回答
  • 2021-01-04 23:22

    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--
    
    0 讨论(0)
提交回复
热议问题