|
|
OverviewA way to upload a file from an HTML form.
Flow
A sample code
use CGI;
use File::Copy;
use File::Basename;
my $q = new CGI;
my $fname = basename($q->param('upfile'));
my $path = ".";
my $newfile = "$path/$fname";
my $fh = $q->upload('upfile');
copy ($fh, "$newfile");
close($fh);
print "Location: upload.html\n\n";
Description of the codeAs an assumption, a file is uploaded from the html page as shown below. This form is assumed to be made as upload.html. <form action="./upload.cgi" method="post" enctype="multipart/form-data"> <input type=file name="upfile"> <input type=submit name=sub value="Uplaod"> </form> Set method to post and specify enctype as multipart/form-data. Make the name of the form of the type=file to ``upfile''. The button name is ``Upload''. use CGI; use File::Copy; use File::Basename; Load the necessary packages. my $q = new CGI; Make a CGI object. At this point, the data from the form are stored into the memory. By using method through this object, various things can be done.
my $fname = basename($q->param('upfile'));
my $path = ".";
my $newfile = "$path/$fname";
Make the file name to be written in the server.
my $fh = $q->upload('upfile');
Make a file handle from the upload method. copy ($fh, "$newfile"); Using copy method of File::Copy, copy the file handle to the file. close($fh); Close the file handle. This should not be necessary. However, in some environemtns, temporary file may remain. By closing the file handle explicity, remove the temporary file. print "Location: upload.html\n\n"; If necessary move to where you want to display next after upload. |