File: Multipart.pm

package info (click to toggle)
libhttp-tiny-multipart-perl 0.08-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 128 kB
  • sloc: perl: 268; makefile: 2
file content (234 lines) | stat: -rw-r--r-- 5,136 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
package HTTP::Tiny::Multipart;

# ABSTRACT: Add post_multipart to HTTP::Tiny

use strict;
use warnings;

use HTTP::Tiny;
use File::Basename;
use Carp;
use MIME::Base64;

our $VERSION = 0.08;

sub _get_boundary {
    my ($headers, $content) = @_;
 
    # Generate and check boundary
    my $boundary;
    my $size = 1;

    while (1) {
        $boundary = encode_base64 join('', map chr(rand 256), 1 .. $size++ * 3);
        $boundary =~ s/\W/X/g;
        last unless grep{ $_ =~ m{$boundary} }@{$content};
    }
 
    # Add boundary to Content-Type header
    my $before = 'multipart/form-data';
    my $after  = '';
    if( defined $headers->{'content-type'} ) {
        if( $headers->{'content-type'} =~ m!^(.*multipart/[^;]+)(.*)$! ) {
            $before = $1;
            $after  = $2;
        }
    }

    $headers->{'content-type'} = "$before; boundary=$boundary$after";
 
    return "--$boundary\x0d\x0a";
}

sub _build_content {
    my ($data) = @_;

    my @params = ref $data eq 'HASH' ? %$data : @$data;
    @params % 2 == 0
        or Carp::croak("form data reference must have an even number of terms\n");
 
    my @terms;
    while( @params ) {
        my ($key, $value) = splice(@params, 0, 2);
        if ( ref $value eq 'ARRAY' ) {
            unshift @params, map { $key => $_ } @$value;
        }
        else {
            my $filename     = '';
            my $content      = $value;
            my $content_type = '';

            if ( ref $value and ref $value eq 'HASH' ) {
                if ( $value->{content} ) {
                    $content = $value->{content};
                }

                if ( $value->{filename} ) {
                    $filename = $value->{filename};
                }
                else {
                    $filename = $key;
                }

                $filename = '; filename="' . basename( $filename ) . '"';

                if ( $value->{content_type} ) {
                    $content_type = "\x0d\x0aContent-Type: " . $value->{content_type};
                }
            }

            push @terms, sprintf "Content-Disposition: form-data; name=\"%s\"%s%s\x0d\x0a\x0d\x0a%s\x0d\x0a",
                $key, 
                $filename,
                $content_type,
                $content;
        }
    }

    return \@terms;
}

no warnings 'redefine';

*HTTP::Tiny::post_multipart = sub {
    my ($self, $url, $data, $args) = @_;

    local $Carp::Internal{ 'HTTP::Tiny::Multipart' } = 1;

    (@_ == 3 || @_ == 4 && ref $args eq 'HASH')
        or Carp::croak(q/Usage: $http->post_multipart(URL, DATAREF, [HASHREF])/ . "\n");

    (ref $data eq 'HASH' || ref $data eq 'ARRAY')
        or Carp::croak("form data must be a hash or array reference\n");
 
    my $headers = {};
    while ( my ($key, $value) = each %{$args->{headers} || {}} ) {
        $headers->{lc $key} = $value;
    }

    my $content_parts = _build_content($data);
    my $boundary      = _get_boundary($headers, $content_parts);

    my $last_boundary = $boundary;
    substr $last_boundary, -2, 0, "--";
 
    return $self->request('POST', $url, {
            %$args,
            content => $boundary . join( $boundary, @{$content_parts}) . $last_boundary,
            headers => $headers,
        }
    );
};

1;

__END__

=pod

=encoding UTF-8

=head1 NAME

HTTP::Tiny::Multipart - Add post_multipart to HTTP::Tiny

=head1 VERSION

version 0.08

=head1 SYNOPSIS

    use HTTP::Tiny;
    use HTTP::Tiny::Multipart;
  
    my $http = HTTP::Tiny->new;
  
    my $content = "This is a test";
  
    my $response = $http->post_multipart( 'http://localhost:3000/', { 
        file => {
            filename => 'test.txt',
            content  => $content,
        }
    } );

creates this request

  POST / HTTP/1.1
  Content-Length: 104
  User-Agent: HTTP-Tiny/0.025
  Content-Type: multipart/form-data; boundary=go7DX
  Connection: close
  Host: localhost:3000
  
  --go7DX
  Content-Disposition: form-data; name="file"; filename="test.txt"
  
  This is a test
  --go7DX--

And

    use HTTP::Tiny;
    use HTTP::Tiny::Multipart;
  
    my $http = HTTP::Tiny->new;
  
    my $content = "This is a test";
  
    my $response = $http->post_multipart( 'http://localhost:3000/', { 
        file => {
            filename => 'test.txt',
            content  => $content,
            content_type  => 'text/plain',
        },
        testfield => 'test'
    } );

creates

  POST / HTTP/1.1
  Content-Length: 104
  User-Agent: HTTP-Tiny/0.025
  Content-Type: multipart/form-data; boundary=go7DX
  Connection: close
  Host: localhost:3000
  
  --go7DX
  Content-Disposition: form-data; name="file"; filename="test.txt"
  Content-Type: text/plain
  
  This is a test
  --go7DX
  Content-Disposition: form-data; name="testfield"
  
  test
  --go7DX--

=head1 CONTRIBUTORS

=over 4

=item * Stephen Thirlwall

=item * Markvy

=item * Infinoid

=item * Mohammad S Anwar

=back

=head1 AUTHOR

Renee Baecker <reneeb@cpan.org>

=head1 COPYRIGHT AND LICENSE

This software is Copyright (c) 2018 by Renee Baecker.

This is free software, licensed under:

  The Artistic License 2.0 (GPL Compatible)

=cut