Perl, Apache2::Request, and uploading files
2009-12-07So I started writing a netboot server for floor. I decided to start writing the web interface first, and learn myself some mason, web perl, and database-y things. Also found some things out about the process that were a little undocumented/misdocumented (now a word).
The biggest issue (so far) was file uploads. So here's a quick tutorial on how to do file uploads with perl, with mason.
In index.html (or wherever your form HTML code lives):
<form method="post" action="upload.mas" enctype="multipart/form-data"> <input type="file" name="file_name" /><br /> <input type="submit" value="Submit" /> </form>
In upload.mas:
<%init> use Apache2::Upload; # $r is an Apache2::RequestRec, not an Apache2::Request like some places say it is my $req = Apache2::Request->new($r); # file_name refers to the form name you had in your HTML my $upload = $req->upload('file_name'); my $fh = $upload->fh; open OUTFILE, ">$where_ever_you_wanna_save_the)file"; binmode $fh; binmode OUTFILE; print OUTFILE $line foreach my $line (<$fh>); close OUTFILE; close $fh; </%init>
In your httpd.conf:
APREQ2_READLIMIT 2G # Sets the max size of your user's uploads to 2GB
I intentionally skipped over error handling code and all of the httpd.conf config for the sake of brevity (I did say brief tutorial). Since I need to allow for larger file sizes than Apache does by default (64MB), I spent quite some time looking for that Apache directive.
Hopefully this saves someone some time.