Site icon Dipin Krishna

Perl: How to Upload a file using perl CGI

perl

This is a tutorial on how to upload a file using perl CGI.

  1. #!/usr/bin/perl -w
  2. use strict;
  3. use CGI;
  4. use CGI::Carp qw ( fatalsToBrowser );
  5. use File::Basename;
  6. $CGI::POST_MAX = 1024 * 5000;
  7.  
  8. my $upload_directory = "/var/www/upload/";
  9. my $cgi = new CGI;
  10. my $filename = $cgi->param("temp_file");
  11.  
  12. if ( $filename ) {
  13.         my ( $name, $path, $extension ) = fileparse ( $filename, '\..*' );
  14.         $filename = $name . $extension;
  15.  
  16.         my $filehandle = $cgi->upload("temp_file");
  17.         open ( my $OUTFILE, ">$upload_directory/$filename" ) or die "$!";
  18.         binmode $OUTFILE;
  19.  
  20.         while( <$filehandle> ) {
  21.                 print $OUTFILE;
  22.         }
  23.  
  24.         close $OUTFILE;
  25.  
  26.         print $cgi->header ( );
  27.         print <<END_HTML;
  28. <html>
  29.         <body>
  30.                 <p>Upload successful!</p>
  31.         </body>
  32. </html>
  33. END_HTML
  34.  
  35. } else {
  36.         print $cgi->header ( );
  37.         print <<END_HTML;
  38. <html>
  39.         <body>
  40.                 <form action="/mod-cgi/upload.cgi" method="post" enctype="multipart/form-data">
  41.                         <input type="file" name="temp_file" />
  42.                         <input type="submit" />
  43.                 </form>
  44.         </body>
  45. </html>
  46. END_HTML
  47.  
  48. }
Exit mobile version