Uploading Files using CGI

Uploading files is a useful thing to know about especially if you want to go about making some kind of admin function for your Web site. There is a very useful form element which is: <input type="file" name="file_data">. This element displays a textbox and a "Browse" button in the browsers which support it:

When you click on the "Browse" button you will get a file dialog where you can choose the file to upload. The HTML is very easy. Now I will look at the CGI Scripting necessary to handle the information from this form.

The CGI Scripting

In fact, the CGI Scripting is pretty simple as well. But you must always remember that the file being uploaded could be a binary file. You just treat the data as you would with any other form value. The data is sent to your CGI script and all you do is access it through some variable such as $data. Then you can manipulate this data and save it to a file if needed. Here is th. Here is the HTML code for a form to upload a file:

<html> <head><title>Simple Uploading example</title></head> <body> <form action="upload.pl" enctype="multipart/form-data"> <input type="file" name="file_data"> <input type="submit" value="Upload!"> </form> </body> </html>

Note the enctype attribute in the <form> tag. This ensures that the file is sent in the correct encoding format. The default is URL-encoded, in which case we don't have to specify enctype, because it defaults to application/x-www-form-urlencoded.

Now to retrieve the data from the form when the user clicks on "Upload". First of all we must realise that the file_data parameter is a file handle, not the data itself. Therefore we can access each line of this data by using the standard <$file_data> format. Here is a sample CGI script which would be able to access the data uploaded and save it into a variable:

<code class="perl">
<l>#!/usr/bin/perl</l>
<l></l>
<l>use CGI qw(:standard);</l>
<l></l>
<l>print header;  # Output header</l>
<l></l>
<l>$in_file=param('file_data');</l>
<l>$data="";</l>
<l></l>
<l>while(&lt;$in_file&gt;){  # Read the file line by line</l>
    <l>   $data.=$_;       # Add each line to this variable</l>
        <l>}</l>
        </code>
        <p>Once you have grasped this simple aspect you can begin writing scripts where you can upload files and save them on the server.</p>