Steven K. Mariner |
Last Updated: 22-Mar-2024 |
CGI File Upload Perl Code Snippet
Nothing gets a programmer up to speed faster than a focused, functional code snippet.
So you have a web page and you want to permit file uploads with it, and Web Page Snippet
Key points:
Perl Snippets
First, we have to grab the filename the user ultimately filled into the form:
Second, we need to strip off the directory information so we're merely writing the output file in the current directory. I think there's a Finally, the snippet you were really looking for, which reads the user-specified file in from the web services standard input device and writes it to the disk in binary mode.
**NOTE** I believe this is often called And that's it. With the example set by these three Don't forget to ensure that your script has both read and write access to the directory where you'll be writing the files. Sometimes you have to go through your web-hosting provider to get some permissions changed.
METHOD field in the FORM tag must be set to "POST" (as opposed to "GET")
File: <INPUT TYPE="FILE" NAME="srcfnm" SIZE=30 MAXLENGTH=255>
<INPUT TYPE="SUBMIT" VALUE="Upload"> <INPUT TYPE="RESET">
</FORM>
$srcfnm = $query->param("srcfnm");
$endcol=length($srcfnm);
$stacol=$endcol;
$staflg=0;
while (!$staflg) {
if (!$stacol) { last; }
$curchr = substr($srcfnm,$stacol-1,1);
if ($curchr eq '\\') { last; }
if ($curchr eq '/') { last; }
if ($curchr eq ':') { last; }
$stacol--;
}
$desfnm = substr($srcfnm,$stacol);
open(RESFIL, ">$desfnm");
binmode(RESFIL);
while ($inpcnt=read($srcfnm,$inpbuf,2096)) {
$inpfsz += $inpcnt;
print RESFIL $inpbuf;
}
close(RESFIL);
© 1997-2024, Steven K. Mariner