Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Fellow Monks,

I'm a newbie to cgi, I am trying fileuploads, and am having trouble getting them to work. The file is created alright, it's just that nothing gets printed into it (I'm trying to upload jpegs). If anybody could show me what I'm doing wrong, it would be greatly appreciated. I am trying this in windows 2000 using IIS webserver.
Here's my snippet:
#!/usr/bin/perl use CGI; use CGI::Carp qw(fatalsToBrowser); #errors will show in the browser my $upload_dir = "C:\\TEMP\\"; my $newStyle; my $co=new CGI; my $filename = $co->param("file");# || error( $co, "No file received." + ); $filename =~ s/.*[\/\\](.*)/$1/; $filename =~ s/[^\w.-]/_/g; my $filehandle = $co->upload("file"); open UPLOADFILE, ">$upload_dir/$filename" or die "Cannot create file $ +upload_dir/$filename: $!\n"; binmode $filehandle; binmode UPLOADFILE; while (defined($_ = <$filehandle>)){ print UPLOADFILE or warn "Possible disk full error: $!\n"; } close UPLOADFILE or warn "Possible truncation on $upload_dir/$filename +: $!\n"; print $co->header, $co->start_html( -title=>'fileupload.cgi', -BGCOLOR=>'#FFFFFF', -style=>{-src=>'http://localhost/html/stylesheet.css', -code=>$newStyle} ), $co->p, "\$filename - <b>$filename</b> moved to the <b>$upload_dir</b> directo +ry!", $co->p, $co->end_html; exit 0;
Thanks in advance,
Jonathan

Replies are listed 'Best First'.
Re: cgi upload incorrectly creating blank files
by eieio (Pilgrim) on Jan 21, 2005 at 14:14 UTC
    I believe you need to specify an encoding of "multipart/form-data" when you create the form in which the file path is specified. You didn't post the code that contains the form with the file input control, but my guess is that its encoding isn't set to "multipart/form-data." This can be done with the CGI object:

    $co->start_form( ..., -enctype=>"multipart/form-data");