Mike Gossland's Perl Tutorial Course for Windows


CGI In Use | Site Search | Presenting Data | Cookies


Chapter 7. CGI In Use

Uploading Files to the Server

Usually when web developers think of uploading files to the server, they're thinking in terms of FTP to get them there. But sometimes it's useful to allow your visitors to upload a picture or a document on the server. 

Have you ever wondered how sites that allow you to upload files to the server through the browser window actually work? You are about to find out how.

The most important thing is that the HTML form's encoding be set to  enctype="multipart/form-data". This advises the server that a file upload is coming in through the CGI interface. An input of type "file" is sufficient to put the Browse button and text box into the form.

When you hit the Upload button, the script at the other end just has to decide where to put the uploaded file, and open a file descriptor to write it there. Then it reads the data in from a specially provided filehandle (courtesy of the CGI module) and it writes it out to the file.

At the end, the directory is opened and the files in the directory are listed. This updated list of files is written back to the upload form so you can see what you just uploaded.

Here's the uploading demo form.

Here's the script that handles the upload.

prev page next page