root/lang/perl/HTTP-Engine/trunk/lib/HTTP/Engine/Role/RequestBuilder/HTTPBody.pm @ 17245

Revision 17245, 2.4 kB (checked in by yappo, 6 years ago)

port a lazy uploads method

Line 
1#!/usr/bin/perl
2
3package HTTP::Engine::Role::RequestBuilder::HTTPBody;
4use Moose::Role;
5
6with qw(
7    HTTP::Engine::Role::RequestBuilder::ReadBody
8);
9
10# tempolary file path for upload file.
11has upload_tmp => (
12    is => 'rw',
13);
14
15has chunk_size => (
16    is      => 'ro',
17    isa     => 'Int',
18    default => 4096,
19);
20
21
22sub _build_http_body {
23    my ( $self, $req ) = @_;
24
25    $self->_read_to_end($req->_read_state);
26
27    return delete $req->_read_state->{data}{http_body};
28}
29
30sub _build_raw_body {
31    my ( $self, $req ) = @_;
32
33    $self->_read_to_end($req->_read_state);
34
35    return delete $req->_read_state->{data}{raw_body};
36}
37
38
39sub _build_read_state {
40    my($self, $req) = @_;
41
42    my $length = $req->header('Content-Length') || 0;
43    my $type   = $req->header('Content-Type');
44
45    my $body = HTTP::Body->new($type, $length);
46    $body->{tmpdir} = $self->upload_tmp if $self->upload_tmp;
47
48    return $self->_read_init({
49        input_handle   => $req->_connection->{input_handle},
50        content_length => $length,
51        read_position  => 0,
52        data => {
53            raw_body      => "",
54            http_body     => $body,
55        },
56    });
57}
58
59sub _handle_read_chunk {
60    my ( $self, $state, $chunk ) = @_;
61
62    my $d = $state->{data};
63
64    $d->{raw_body} .= $chunk;
65    $d->{http_body}->add($chunk);
66}
67
68sub _prepare_uploads  {
69    my($self, $c) = @_;
70
71    my $req     = $c->req;
72    my $uploads = $req->http_body->upload;
73    my %uploads;
74    for my $name (keys %{ $uploads }) {
75        my $files = $uploads->{$name};
76        $files = ref $files eq 'ARRAY' ? $files : [$files];
77
78        my @uploads;
79        for my $upload (@{ $files }) {
80            my $u = HTTP::Engine::Request::Upload->new;
81            $u->headers(HTTP::Headers->new(%{ $upload->{headers} }));
82            $u->type($u->headers->content_type);
83            $u->tempname($upload->{tempname});
84            $u->size($upload->{size});
85            $u->filename($upload->{filename});
86            push @uploads, $u;
87        }
88        $uploads{$name} = @uploads > 1 ? \@uploads : $uploads[0];
89
90        # support access to the filename as a normal param
91        my @filenames = map { $_->{filename} } @uploads;
92        $req->parameters->{$name} =  @filenames > 1 ? \@filenames : $filenames[0];
93    }
94    return \%uploads;
95}
96
97__PACKAGE__
98
99__END__
100
101=pod
102
103=head1 NAME
104
105HTTP::Engine::Role::RequestBuilder::HTTPBody -
106
107=head1 SYNOPSIS
108
109        use HTTP::Engine::Role::RequestBuilder::HTTPBody;
110
111=head1 DESCRIPTION
112
113=cut
114
115
Note: See TracBrowser for help on using the browser.