Wednesday, October 22, 2014

File uploading script using CGI in Perl

Following is a simple example of uploading a file in the web server using Perl.

#!/usr/bin/perl

use CGI; # required module for CGI scripting

print "content-type: text/html \n\n";

my $q = new CGI; # create a CGI object

my $upload = $q->param("upload"); # using CGI param method to accept value passed to the program as a parameter

if ($upload) {
 &upload_file();
}
else
{
 &form();
}

sub form 
{
 print qq{
  
Upload Photo:
}; } sub upload_file { my $upload_dir = "/var/www/html/test"; my $filename = $q->param("photo"); # fetching the uploaded file name passed as posted parameter $filename =~ s/.*[\/\\](.*)/$1/; my $upload_filehandle = $q->upload("photo"); # fetching the content of the uploaded file open FL, ">$upload_dir/$filename"; while ( <$upload_filehandle> ) { print FL; } close FL; print qq{ Thankyou for uploading your photo!!!
}; }

Output:
-------
Considering the above script filename to be 'file_upload.pl' present inside the location '/var/www/cgi-bin/test/' of the web server, to checkout the file uploading functionality, please call the above script in the following format from a web browser:

http://server_address/cgi-bin/test/file_upload.pl