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

Hi, Please go through my code. I am trying to upload files to server using a form. The file is created in the proper place but content is blank (size is zero). I didn't get any idea to debug this... here is my code ...
$fname =$query->param('filename'); $upload_dir="/usr/web/doc"; $upfile=$fname; $upfile=~ s/\\/\//g; ## Replace all \'s with /'s. ## Extract the upload file's name. @path=split(/\//,$upfile); $upload_file= $upload_dir."/".$path[$#path]; open(MYFILE,">$upload_file") || die $!; binmode MYFILE; while($bytesread=read($fname,$data,1024)) { $size+=$bytesread; print MYFILE $data; } close(MYFILE);
Thanks

Edit: Added <code> tags. larsen

Replies are listed 'Best First'.
Re: uploaded file is not proper
by Skeeve (Parson) on Jun 16, 2003 at 07:59 UTC
    You forgot:
    1. to open $fname for reading
    2. the <code>-tags ;-)
Re: uploaded file is not proper
by barrd (Canon) on Jun 16, 2003 at 11:11 UTC
    Hello anonymous,
    Try replacing from open() to close() with this snippet:

    open(MYFILE, ">$upload_file") || die "Couldn't open upload file: $!\n" +; print MYFILE while (<$fname>); close(MYFILE) || die "Couldn't upload file: $!\n";

    This won't give you the file size that you where attempting to assign into $size but 'should' work as far as the upload is concerned. If that works you can then work on getting the size of the file afterwards, this is only to ensure that you can get the upload to work 'at all'.

    On matters of security:

    I'd *really* add a little foreach loop going through an array of accepted acceptable file extensions (mime types) before the upload section, and then chmod the uploaded file to read only, but that's only IMHO (call me paranoid).

    Update: Corrected grammar and added "(mime types)"

(jeffa) Re: uploaded file is not proper
by jeffa (Bishop) on Jun 16, 2003 at 15:20 UTC
    Adding on to the advice already given, you really should be using CGI.pm's upload() instead of param() to upload a file:
      To be safe, use the upload() function (new in version
      2.47).  When called with the name of an upload field,
      upload() returns a filehandle, or undef if the parameter
      is not a valid filehandle.
    
         $fh = $query->upload('uploaded_file');
         while (<$fh>) {
            print;
         }
    
      In an array context, upload() will return an array of
      filehandles.  This makes it possible to create forms that
      use the same name for multiple upload fields.
    
      This is the recommended idiom.
    

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    
Re: uploaded file is not proper
by Anonymous Monk on Jun 16, 2003 at 09:41 UTC
    check your form tag in the html page.. that will cause these type of problems.. sureshp