Thursday, September 20, 2007

Using PERL to create a file upload script

sub upload_file {
my ($data, $filename);
my $file = param( 'upload' );
my $type = uploadInfo($file)->{'Content-Type'};

if (!$file) {
print "No file uploaded!";
($filename = $file) =~ s /^\w.+\\//ig;
print $filename, br;
print $file,br,$type,br;
open (SAVE,">./$filename") ¦¦ die $!;
while (read($file,$data,1024)) {
print SAVE $data;
close SAVE;

comment for the perl codes:

This is using, correct?

I may be off on this part, but try changing

while (read($file,$data,1024))


while (read($file,$buffer,1024))

I seem to recall finding $buffer being one of the variables used in that if changed it won't work. (This part may be inaccurate, but it's one variable and you can change it back, try it.)

Secondly, you have verified your substitution indeed grabs the right filename, correct? Beware, this is a double-edged sword - Mac paths do not follow the / syntax. I do something like

@fullpath = split (/\\¦\/¦:/,$file); ## \ for win / for linux : for mac
$filename = $fullpath[$#fullpath]; ## or use pop(@fullpath)

Last thing you could look at is

open (SAVE,">./$filename")

./ from where? I've noticed when working with, your location at the time this bit of code runs is not where you think. I've seen my files turn up in the CGI_temp directory, the server root . . . all kinds of places. Try

$filename = /full_virtual_path/to/$filename;

So all together:

@fullpath = split (/\\¦\/¦:/,$file);
$filename = pop(@fullpath);
$filename = /full_virtual_path/to/$filename;

open (SAVE,">$filename") ¦¦ die $!;
while (read($file,$buffer,1024)) {
print SAVE $buffer;
close ($file); ##old habit - maybe bad one but it works
close SAVE;

No comments: