About Mikazo Tech Blog

My name is Mike, and this blog is my way of saving people time. If someone has a specific problem that I've encountered before, hopefully these posts will save them the extraneous Googling I had to go through to solve the same problem. Also, when I have something to say about technology today, I will post my thoughts here. If this blog has helped you out, even a little bit, vote on the poll below, or let me know by sending me an email. I'm always open to exchanging links with other blogs or websites that share a similar interest.

Thursday, March 19, 2009

How To Upload Files with Perl and CGI

I took me quite a while of sifting through the internet looking how to do this. I played with different CGI.pm functions, and so on, but eventually sort of improvised my own script based on what I've seen. This script takes a method="get" parameter of the form "c:\folder1\folder2\file.txt". It does not do any string sanitation or error checking, it just uploads the file. I had to edit the stupid HTML brackets because Blogger doesn't like me typing it there. You'll have to replace the (less/greater than sign) with the actual symbol. Feel free to use if you want.

Code:

use CGI;

$query = new CGI;
print $query->header;
print $query->start_html('Upload file');

$form = $ENV{'QUERY_STRING'};
@args = split('=', $form);
$args[1] =~ s/%3A/:/g;
$args[1] =~ s/%5C/\\/g;
@pieces = split('\\\\', $args[1]);
$length = @pieces;
$localpath = "";
for ($i=0; $i<=$length-2; $i++) {
$localpath .= "$pieces[$i]\\";
}
$localname = $pieces[$length-1];
print "Uploading $localpath$localname";
$serverfile = $ENV{'DOCUMENT_ROOT'} . "/assgn3/cont/$localname";

open(FILEIN, "<$localpath$localname");
open(FILEOUT, ">$serverfile");
while ($line =
(less than sign)FILEIN(greater than sign)) {
print FILEOUT $line;
}
close FILEIN;
close FILEOUT;

print "Upload successful, redirecting to main.pl";
print "(less than sign)meta http-equiv='Refresh' content='4; url=main.pl'(greater than sign)";
print "
(less than sign)/body(greater than sign)(less than sign)/html(greater than sign)";


0 comments:

Donate to Mikazo Tech Blog