Skip to content
Blog Perl: How to Upload a file using perl CGI

Perl: How to Upload a file using perl CGI

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

#!/usr/bin/perl -w
use strict;
use CGI;
use CGI::Carp qw ( fatalsToBrowser );
use File::Basename;
$CGI::POST_MAX = 1024 * 5000;

my $upload_directory = "/var/www/upload/";
my $cgi = new CGI;
my $filename = $cgi->param("temp_file");

if ( $filename ) {
        my ( $name, $path, $extension ) = fileparse ( $filename, '\..*' );
        $filename = $name . $extension;

        my $filehandle = $cgi->upload("temp_file");
        open ( my $OUTFILE, ">$upload_directory/$filename" ) or die "$!";
        binmode $OUTFILE;

        while( <$filehandle> ) {
                print $OUTFILE;
        }

        close $OUTFILE;

        print $cgi->header ( );
        print <
        
                

Upload successful!

END_HTML } else { print $cgi->header ( ); print <
END_HTML }

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.