Mike
Mike

Reputation: 111

upload file through Perl CGI script without storing file

I created a CGI script in Perl which uploads a file to the server. The script works perfectly:

my $upload_filehandle = $query->upload("config");

if (!$upload_filehandle)
{
    die "Configuration file could not be loaded";
}

open ( UPLOADFILE, ">$upload_dir/$filename" ) or die "$!";
binmode UPLOADFILE;

while ( <$upload_filehandle> )
{
    print UPLOADFILE;
}

close UPLOADFILE;

The problem is that I do not want to store the file onto the server but only want to store a part of its contents inside some variables in the Perl script. I do not know how to do this. I tried the following piece of code instead:

my @array;
my $upload_filehandle = $query->upload("config");

if (!$upload_filehandle)
{
    die "Configuration file could not be loaded";
}

open ( UPLOADFILE, ">$upload_dir/$filename" ) or die "$!";
binmode UPLOADFILE;

while ( <$upload_filehandle> )
{
    push @array, $_;
}


close UPLOADFILE;

I want to store the file contents in an array but it gives an error:

[Sat Aug 31 18:03:27 2013] [error] [client 127.0.0.1] malformed header from script. Bad      header=\xff\xd8\xff\xe11\xdcExif: loadConfig.cgi, referer: http://localhost/cgi-bin/uploadFile.cgi

I think it is at line push @array, $_; and it maybe caused because the header of the file is not recognized.

Do you have any ideas about how to store the file content without saving the file?

Thank you in advance for your response.

Upvotes: 1

Views: 644

Answers (1)

RobEarl
RobEarl

Reputation: 7912

It looks like you're trying to print the file (\xff\xd8\xff\xe11\xdcExif) before a proper HTTP header:

print $query->header;

I've tidied up your script a little and this works fine:

#!/usr/bin/perl

use strict;
use warnings;

use CGI;
use CGI::Carp 'fatalsToBrowser';

my $query = CGI->new;

my $upload_filehandle = $query->upload("config")
    or die "Configuration file could not be loaded";


my @array = <$upload_filehandle>;

print $query->header;

use Data::Dumper;
print Dumper(\@array);

Upvotes: 1

Related Questions