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

G'Day Monks

I'm having a bit of trouble with a CGI script I'm working on. I want my users to be able to upload a file to a certain directory. I have printed up an HTML form in which they specify the full path and name of the file they wish to upload. Here's the code:
print $cgi->header; print $cgi->start_html(-title=>'Upload New File'); print <<EOP; <p align=center><h2>Use the form below to upload a new file</h2></ +p> <hr> <form enctype="multipart/form-data" method=post> <p align=center><input type=file name="file" size=50></p> <p align=center><input type=submit value=Upload></p> EOP
The script is mainly targeted at Windows users, so the sort of paths I'm getting are similar to C:\Documents and Settings\Administrator\My Documents\somedocument.doc. The trouble is, after they click the submit button, the path I'm getting is only whatever is after the last backslash in the path. In the example I just gave, the 'file' parameter I get is somedocument.doc.

I know I could solve this problem by having the user enclose the path in quote marks, but I'd rather not have to have them do that. Any suggestions? Is there a way to automatically enclose the filename they enter in quotes? Or some way to ensure I get the full path?

Thanks for the help! I appreciate it.

Replies are listed 'Best First'.
Re: File Upload Problem
by Snuggle (Friar) on Jul 02, 2002 at 15:34 UTC
    The parameter returned in multipart form data when accessed the first time is the filename of the file uploaded (like you said, JUST the filename). You need to ensure that you are eliminating illegal characters, usually with a RegEx of some type. Then you can execute something like this:
    while (my $bytesread = read($file, my $buffer, 1024)) { print OUTFILE $buffer; }

    to get the actual data from the file (you have to have defined OUTFILE, usually as the filename you just got from the form parameter). There isn't a real way to get multipart form data to send you the full path to the file on the users computer, nor do you need it.

    Check out this node for more great info.

    Anyway, no drug, not even alcohol, causes the fundamental ills of society. If we're looking for the source of our troubles, we shouldn't test people for drugs, we should test them for stupidity, ignorance, greed and love of power.

    --P. J. O'Rourke