Sunday 27 May 2018

Uploading files to web pages

This turned out to be a bit more tricky than I had thought.

You have to use a cgi that starts off like this:

 <FORM method="post" action="upload.cgi" ENCTYPE="multipart/form-data">

And then there will be various elements to the form, depending on what other data you want, and then:

Upload:          <INPUT TYPE=file NAME=filename>

Then you parse the result of the cgi using

use CGI::cgi_lite;

$cgi = new CGI_Lite ();
$cgi->set_directory ($images) || die "Directory $images doesn't exist.\n";
$cgi->set_file_type ("handle");
%in = $cgi->parse_form_data ();

The name of the file will be in $in{'filename'};

And the file itself will be in the $images directory that you set. But, the filename will have an extra 11 characters appended to it, that's to ensure that the name is unique. If you want the original filename, you have to strip those off.

Then the thing that really threw me. If the original filename contains spaces, then $in{'filename'} doesn't contain the filename, it contains the bytes of the file itself!
I have no idea why.

open UPLOAD, ">$images/upload.file";
binmode UPLOAD;
print UPLOAD $in{'filename'};
close UPLOAD;

Then you'll have to rename the file to something unique.

No comments:

Post a Comment