Why is this Perl CGI script failing to upload imag

2019-07-27 09:54发布

问题:

I have this code:

use CGI;    
use File::Basename;    
use Image::Magick;    
use Time::HiRes qw(gettimeofday);    
my $query = new CGI;    
my $upload_dir = "../images"; #location on our server    
my $filename=$query->param("img");    
my $timestamp = int (gettimeofday * 1000);    
my ( $name, $path, $extension ) = fileparse ( $filename, '\..*' );     
$filename = $name ."_".$timestamp. $extension;    

 #upload the image

my $upload_filehandle =$query->param("img");    
open ( UPLOADFILE, ">$upload_dir/$filename" ) or die "$!";  
 binmode UPLOADFILE;  
 while ( <$upload_filehandle> )  
  {  
   print UPLOADFILE;  
   }  

  close UPLOADFILE;

Then I do resize for the image. My problem is that the image is not uploaded. I have an empty file having the name of $filename. I omitted the part related to resize and I still have the code. So I'm sure that the file is not being uploaded correctly. Am I missing any library? Any help?Plz..

回答1:

You need to change

my $upload_filehandle =$query->param("img");

to

my $upload_filehandle =$query->upload("img");

according to this tutorial.

Hope it helps.



回答2:

I figured out why: As pointed out in the CGI.pm docs, the form's encoding type must be multipart/form-data. When I added that, everything worked.



回答3:

added this "ENCTYPE='multipart/form-data'" instead of encoding.

> <form action="/post.pl" method="post"  ENCTYPE='multipart/form-data'>

and it worked