Inside JavaScript
Here's an example using the file upload element; in this case, I'll upload a file named file.txt with the contents: Here is the text in the file.... In this example, the user can select a file to upload and press the Upload button we'll supply. (This button is just a submit button that uploads the form's data, including the file specified in the file control.) When the user does so, the code will ask the user if he is sure that he wants to upload the file, reading the name of the file from the file control's value property. Here's what that code looks like: (Listing 13-13.html on the web site)
<HTML> <HEAD> <TITLE> CGI File Upload Example </TITLE> <SCRIPT LANGUAGE="JavaScript"> <!-- function dataWarn() { if (confirm("Are you sure you want to upload " + document.form1.filename.value + "?")) { return true } else { return false } } // --> </SCRIPT> </HEAD> <BODY> <H1>CGI File Upload Example</H1> <FORM METHOD="POST" NAME="form1" ACTION="http://www.starpowder.com/steve/cgiupload.cgi" ENCTYPE="multipart/form-data" ONSUBMIT="return dataWarn()"> <INPUT TYPE="FILE" NAME="filename" SIZE="30"> <BR> <INPUT TYPE="SUBMIT" NAME="submit" VALUE="Upload"> <INPUT TYPE="RESET"> </FORM> </BODY> </HTML> You can see this page at work in Figure 13.16, where the code is asking the user whether he really wants to upload the file. Clicking OK uploads the file, clicking Cancel cancels the operation. Figure 13.16. Using a file upload control.
To handle the file's data when it arrives on the server, I'll use a Perl CGI script, whose URL is given in the ACTION attribute of the form in our example. (The URL is fictitious.) Here's the Perl code that will read the file and display its contents by sending a web page back to the browser (more on Perl CGI scripts in Chapter 24, ".NET and Security"): (Listing 13-14.cgi on the web site)
#!/usr/local/bin/perl use CGI; $co = new CGI; print $co->header, $co->start_html( -title=>'CGI Example', -author=>'Steve', -meta=>{'keywords'=>'CGI Perl'}, ); $file = $co->param('filename'); @data = <$file>; foreach (@data) { s/\n/<br>/g; } print $co->center($co->h2("Here's what was in $file:")), "@data"; print $co->end_html; You can see the results in Figure 13.17, where you see the uploaded text from the file. Figure 13.17. The text of an uploaded file.
And that's it. That completes our chapter. We've come far in this chapter, handling text controls such as text fields, password controls, hidden controls, text areas, select controls and option elements, and now file upload controls. In the next chapter, we'll get the details on links, lists, and working with tables in JavaScript. |