#!/usr/bin/perl -wT # Name: file_upload.cgi # Written by: Matt Doyle # Obtained from: http://www.sitepoint.com/uploading-files-cgi-perl-2/ # Obtained on: November 13, 2011 # Last modified: November 13, 2001 # Modified by: Jim Cameron # URL: support.moonpoint.com/downloads/computer_languages/perl/file_upload # Version: 0.1 # Notes: change the value of upload_dir to match the directory on your # server where uploaded files should be placed. The maximum size for # uploaded files is controlled by $CGI::POST_MAX. I've set the default # value to 15 MB (15000); you can change that, if needed, depending on # the size of files you wish to allow to be uploaded to your site. use strict; use CGI; # Remove the comment char from the beginning of the line below for debugging # use CGI::Carp qw ( fatalsToBrowser ); use File::Basename; use File::stat; # Display a file's size in a more human friendly form, i.e., use # MB, GB, etc. as appropriate rather than just bytes for larger files # # From Stuart's Useful Perl Pages # http://www.jb.man.ac.uk/~slowe/perl/filesize.html sub niceSize { # Will work up to considerable file sizes! my $size = 0; my $fs = $_[0]; # First variable is the size in bytes my $dp = $_[1]; # Number of decimal places required my @units = ('bytes','kB','MB','GB','TB','PB','EB','ZB','YB'); my $u = 0; $dp = ($dp > 0) ? 10**$dp : 1; while($fs > 1024){ $fs /= 1024; $u++; } if($units[$u]){ return (int($fs*$dp)/$dp)." ".$units[$u]; } else{ return int($size); } } # The maximum file upload size is currently set to 15 MB. Change the 15000 # to whatever value you want if that is too large or too small for your site. $CGI::POST_MAX = 1024 * 15000; my $safe_filename_characters = "a-zA-Z0-9_.-"; # Change the upload_dir value to the directory where files should be # placed on your website when they are uploaded. my $upload_dir = "/home/jdoe/www/uploads"; my $query = new CGI; my $filename = $query->param("upfilename"); if ( !$filename ) { print $query->header ( ); print "There was a problem uploading your upfilename (try a smaller file)."; exit; } my ( $name, $path, $extension ) = fileparse ( $filename, '\..*' ); $filename = $name . $extension; $filename =~ tr/ /_/; $filename =~ s/[^$safe_filename_characters]//g; if ( $filename =~ /^([$safe_filename_characters]+)$/ ) { $filename = $1; } else { die "Filename contains invalid characters"; } my $upload_filehandle = $query->upload("upfilename"); open ( UPLOADFILE, ">$upload_dir/$filename" ) or die "$!"; binmode UPLOADFILE; while ( <$upload_filehandle> ) { print UPLOADFILE; } close UPLOADFILE; my $sb = stat("$upload_dir/$filename"); my $filesize = $sb->size; my $size = &niceSize($filesize,2); print $query->header ( ); print < File Uploaded

File upload completed!

File uploaded: $filename
File size: $size ($filesize bytes)

END_HTML