Every single time I try to implement file uploads via the web, I forget the ‘enctype’ attribute that needs to be in the form tag in the HTML:
<form enctype="multipart/form-data" method="post" action="/path_to/my_script">
If you forget that like I do, your server side program will receive the filepath information from the ‘file’ input on the form…
<input type="file" name="attachment">
… but it won’t receive the file data itself. I struggle with this every time, thinking something is wrong with the code on server, until it dawns on me. I’m really just writing it here in hopes I never, ever forget again.
To complicate matters, Perl’s CGI module accepts the parameter from the form…
my $attachment = $cgiobject->param('attachment');
…with both values, the file path and the file data itself, stuffed into the same variable (here called $attachment), which coughs you up the file path when used in scalar context…
# prints the local filepath the file was uploaded from
print $attachment;
…and the file data when used in a filehandle context. Here is the piece where I save the file data to a directory on server:
open (UPLOADFILE, "> attachments/$final_filename") or die "$!";
binmode UPLOADFILE;
while(<$attachment>) {
print UPLOADFILE;
}
Notice we are still just referencing that same $attachment variable which was grabbed from the CGI input. This is hard to wrap your head around at first and frankly I’m not even sure how this magic is accomplished. A scalar variable with two values depending on context is whacky, but it does work.