Skip to content

Commit

Permalink
Altered HTTP::Lite library to support streaming uploading of files.
Browse files Browse the repository at this point in the history
To upload a file use the following code:

  #Create http object
  my $http = new HTTP::Lite;
  #Set the content type
  $http->add_req_header('Content-Type', 'application/octet-stream');
  #Set the request method
  $http->method('POST');
  #Set the file that has to be uploaded
  $http->{'content'} = {'file' => <FILENAME>};
  #Make the request
  $http->request(<URL>);

This code will send a 'POST' request to <URL> and the file <FILENAME> will be streamed as the body of the request.
  • Loading branch information
Jan van Nunen authored and maikelsteneker committed Mar 10, 2020
1 parent 85d2914 commit e319675
Showing 1 changed file with 28 additions and 7 deletions.
35 changes: 28 additions & 7 deletions lib/HTTP/Lite.pm
Original file line number Diff line number Diff line change
Expand Up @@ -217,9 +217,10 @@ sub request
if (!defined($self->get_req_header("Accept"))) {
$self->add_req_header("Accept", "*/*");
}

if ($method eq 'POST') {
$self->http_write(*FH, "Content-Type: application/x-www-form-urlencoded$CRLF");
my $content_type =
$self->get_req_header("Content-Type") || $method eq 'POST' && 'application/x-www-form-urlencoded';
if ($content_type) {
$self->http_write(*FH, "Content-Type: $content_type$CRLF");
}

# Purge a couple others
Expand All @@ -236,7 +237,11 @@ sub request
my $content_length;
if (defined($self->{content}))
{
$content_length = length($self->{content});
if (!ref $self->{content}) {
$content_length = length($self->{content});
} elsif (ref $self->{content} eq 'HASH' && defined $self->{content}->{'file'}) {
$content_length = -s $self->{content}->{'file'};
}
}
if (defined($callback_func)) {
my $ncontent_length = &$callback_func($self, "content-length", undef, @$callback_params);
Expand Down Expand Up @@ -269,9 +274,25 @@ sub request
}

# Output content, if any
if (!$content_out && defined($self->{content}))
{
$self->http_write(*FH, $self->{content});
if (!$content_out && defined($self->{content})) {
if (!ref $self->{content}) {
$self->http_write(*FH, $self->{content});
} elsif (
ref $self->{content} eq 'HASH' &&
defined $self->{content}->{'file'} &&
-r $self->{content}->{'file'}
) {
local *FILE;
my $data;

if (open(FILE, '<', $self->{content}->{'file'})) {
binmode(FILE);
while (read(FILE, $data, 1024)) {
$self->http_write(*FH, $data);
}
close(FILE);
}
}
}

if (defined($callback_func)) {
Expand Down

0 comments on commit e319675

Please sign in to comment.