Home  |  Linux  | Mysql  | PHP  | XML
From:ngophuochau Date:Sun May 25 21:57:23 2003
Subject:upload.cgi
Hi!
I have been studying with the O'Reilly book - "CGI programing with Perl" - chapter 5-page 99.
Below is the script of upload.cgi that utilizes CGI.pm. I am not able to get it to work correctly yet. I don't know why ( sorry! i am new ).
In "uploads" directory , i just received the filename uploaded but its content was empty.
Please help me!
Any help extremely appreciated!
Here is my script:
#!/usr/bin/perl -wT

use strict;
use CGI;
use Fcntl qw( :DEFAULT :flock );

# use constant UPLOAD_DIR => "/usr/local/bin";
use constant UPLOAD_DIR  => " /usr/local/bin/uploads/";
use constant BUFFER_SIZE =>16_384;
use constant MAX_FILE_SIZE => 100 * 1_048_576;
use constant MAX_DIR_SIZE => 100 * 1_048_576;
use constant MAX_OPEN_TRIES =>100;

$CGI::DISABLE_UPLOADS    = 0;
$CGI::POST_MAX           = MAX_FILE_SIZE;

my $q = new CGI;
$q->cgi_error and error( $q, "Error transferring file: ". $q->cgi_error );

my $file       = $q->param( "file" )        || error( $q, "No file
recieved." );
my $filename   = $q->param( "filename" )    || error( $q, "No filename
entered." );
my $fh         = $q->upload( $file );
my $buffer     = "";

if ( dir_size( UPLOAD_DIR ) + $ENV{CONTENT_LENGTH} > MAX_DIR_SIZE ) {
    error( $q, "Upload directory is full." );
}

# Convert odd ball characters to underscore
$filename =~ s/[^\w.-]/_/g;
if ( $filename =~ /^(\w[\w.-]*)/ ) {
     $filename = $1;
}
else {
     error( $q, "Invalid file name; files must start with a letter or
number." );
}

# open output file, making sure the file name is unique
until ( sysopen OUTPUT, UPLOAD_DIR . $filename, O_CREAT | O_EXCL ) {
    $filename =~ s/(\d*)(\.\w+)$/($1||0) + 1 . $2/e;
    $1 >= MAX_OPEN_TRIES and error( $q, "Unable to save your file." );
}
# This is neccessary for non-Unix systems does nothing on UNIX
binmode $fh;
binmode OUTPUT;

# write contents to output file
while ( read($fh, $buffer, BUFFER_SIZE ) ) {
   print OUTPUT $buffer;
}

close OUTPUT;

sub dir_size {
   my $dir = shift;
   my $dir_size = 0;


   # loop through files and sume the sizes; doesn't decend down subdirs
   opendir DIR, $dir or die "Unable to open $dir: $!";
   while ( readdir DIR ) {
      $dir_size += -s "$dir/$_";
   }
     return $dir_size;
}

sub error {
   my( $q, $reason ) = @_;

  print $q->header( "text/html" ),
        $q->start_html( "Error" ),
        $q->h1( "Error" ),
        $q->p( "Your upload was not processed because the following error",
"occured: "),
        $q->p( $q->i( $reason )),
        $q->end_html;
     exit;
}




---------------------------------
Do you Yahoo!?
The New Yahoo! Search - Faster. Easier. Bingo.
Navigate in group perl.macperl.webcgi at sever nntp.perl.org
Previous Next




  
© No Copyright
You are free to use Anything
Site Maintained by PHP Developer
Powered By PHP Consultants