Uploading a file

Top Japanese page




Overview

A way to upload a file from an HTML form.

Flow

  1. Load CGI, File::Copy, File::Basename
  2. Make an object of CGI
  3. Set a file name to be written on the server
  4. Open the uploaded file and make a file handle
  5. Copy the file handle to the file specified
  6. Close the file handleファイルハンドルをクローズする。
  7. If necessary, jump to an html page

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 code

As 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. $q->param('upfile') gets the file name passed from the input form. And basename removes the path name from it. Then make a new file name including the path to be written.

 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.