Monday, November 5, 2007

Perl file upload

hey guys

it has been long since i have posted any code online.Got a bit busy with my work @ my office.But people i am back and wanted to do something even better this time .so i thought i should open a blog where all my codes can reside.i have done lot of file uploading in php and then i bumped into a project where i was required to do file uploading in perl.Long back my freind was trying to do the same and he told me that its tough to do so.but i never looked into it at that time and now i started writing the code for the same with a small fear in mind(Thanks to my freind) that the code will take a toll on my grey cells.but it didnot.Its so simple.
Here it goes

here is the html code for file upload
<form action="upload.cgi" method="post" enctype="multipart/form-data" onsubmit="return checkfile();">

<table align="center" border="0" cellpadding="0" cellspacing="0">
<tbody><tr><td align="center"><b>File upload by rohit d'souza</b></td></tr>
<tr><td align="center">
</td></tr>
<tr><td>
</td></tr>
<tr><td>
</td></tr>
<tr><td align="center">
File to Upload: <input name="filerohit" type="file">


<input name="Submit" value="Submit Form" type="submit">
</td>
</tr>
<tr><td>
</td></tr>
<tr><td>
</td></tr>
</tbody></table>
</form>

here checkfile is a javascript function to check if the user has actaully selected a file before submitting the form.

function checkfile()
{

if(document.forms[0].filerohit.value=="")
{
alert("please select a file to upload");
return false;

}


}


here is the server side code in upload.cgi
#!/usr/bin/perl


use CGI;
use strict;
my $query = new CGI;
my $upload_dir="/opt/myuploads";
my $filename = $query->param("filerohit");
$filename =~ s/.*[\/\\](.*)/$1/;
my $upload_filehandle = $query->upload("filerohit");

open UPLOADFILE, ">$upload_dir/$filename";

binmode UPLOADFILE;

while ( <$upload_filehandle> )
{
print UPLOADFILE;
}

close UPLOADFILE;


and now u can do anything u want with the file which is at the location $upload_dir/$filename

Thats all.hope this code helps u.u could send me ur feedbacks at rajdsouza@yahoo.com