How to Upload Files From Html Form in Perl

Would yous like to requite your visitors the ability to upload files to your site? Letting them upload content with their Spider web browsers can be very useful, and fun too! Yous can let them contribute pictures, sounds and other binary files to your site. And you tin apply a file upload facility on your own Website to update your site's content easily via your own Web browser.

If you lot've e'er used a Web-based email service such as Yahoo! Mail or Hotmail, yous've probably sent email with attachments. To add attachments to your emails, you simply click the "Browse..." push on the Web page to select the file from your hard drive, and then your browser sends the file to the server. This is file upload in action!

But how does it piece of work? In this article I'm going to talk you through the process of file upload, and bear witness you how to build a simple file upload instance using CGI and Perl. The example we'll go through will allow people to upload photos of themselves to your Spider web server.


What Y'all'll Demand
To build your ain file upload script, you'll need the post-obit:

  • Access to a Web server that supports CGI (nearly all exercise)
  • A copy of Perl running on the Web server
  • The Perl CGI library, CGI.pm, installed on your Web server. This is probably pre-installed, but if information technology's not, you can grab it here.


How Does It Work?

File upload works by using a special type of form field called "file", and a special type of class encoding called "multipart/form-information". The file form field displays a text box for the filename of the file to upload, and a "Scan..." button:

474browsebutton

The user clicks the "Browse..." button to bring up the file selector, and chooses the file they wish to upload. Then, when they click the "Submit" button on the grade, the file'due south data is uploaded to the Web server, along with the rest of the class's data:

474transferdiag

At the Spider web server finish, the software (in our example, a CGI script) interprets the form data that's sent from the browser, and extracts the file proper noun and contents, along with the other class fields. Ordinarily, the file is then saved to a directory on the server.

Now, let's create a file upload grade that allows your users to upload files to your Web server.


Creating the File Upload Form

i. The Form Tag

The starting time line of code for a file upload form is the Form tag, as follows:

                                  <Grade ACTION="/cgi-bin/upload.cgi" METHOD="mail"                  
ENCTYPE="multipart/form-information">

Annotation the special multipart/form-data encoding type, which is what we use for file upload. Note also that the course will post the data to our upload script, called upload.cgi , which nosotros'll create in the next section.

2. The INPUT Type=FILE Tag

The 2d part of the file upload grade is the upload field itself. In this example we're creating a form then that our users can upload their photos, and then we need an upload field called "photo":

Photo to Upload: <INPUT Blazon="file" Proper noun="photo">

three. Other INPUT Tags

You can include other, normal form fields in your form too as the INPUT TYPE=FILE field. Hither we're going to allow the user to submit their email address along with their photo:

Your Email Address: <INPUT Type="text" NAME="email_address">

4. The Submit Button

As with a regular form, we need a "Submit" button and then that the user can send the form to the Web server:

<INPUT Blazon="submit" NAME="Submit" VALUE="Submit Grade">

The Finished Form

So our consummate file upload grade looks like this:

                <HTML>
<HEAD></HEAD>
<Torso>
<FORM ACTION="upload.cgi" METHOD="post" ENCTYPE="multipart/form-data">
Photo to Upload: <INPUT TYPE="file" Proper noun="photo">
<br><br>
Your Email Accost: <INPUT Blazon="text" Name="email_address">
<br><br>
<INPUT TYPE="submit" Name="Submit" VALUE="Submit Form">
</FORM>
</Trunk>
</HTML>

Save this file somewhere on your hard bulldoze, and call it something similar "file_upload.html" .

So far so good! Now allow's look at how to write the server CGI script, upload.cgi .

Creating the File Upload Script

Handling the information that the browser sends when it uploads a file is quite a complex procedure. Fortunately, the Perl CGI library, CGI.pm, does nearly of the dirty piece of work for us!

Using ii methods of the CGI query object, param() and upload() , nosotros can retrieve the uploaded file'south filename and file handle respectively. Using the file handle, we can read the contents of the file, and save it out to a new file in our file upload expanse on the server.

i. Commencement Things First

The beginning things nosotros demand to practice in our script are, of course, create the shebang line, and utilise the Perl CGI library:

                                  #!/usr/bin/perl -w

utilize CGI;

Note the utilise of the -w to make Perl warn us of any potential dangers in our code. It's about always a good idea to put the -w in!

2. The Upload Directory

We demand a location on our server where we can shop the uploaded files. We want these files (photos) to be visible on our Website, so we should shop them in a directory nether our document root, for case:

                                  $upload_dir = "/home/mywebsite/htdocs/upload";              

So you'll demand to create a directory called "upload" on your Website'due south certificate root, then fix $upload_dir to the absolute path to that directory, equally I've done to a higher place.

three. Reading the Form Variables

The next step is to read in the filename of our uploaded file, and the e-mail address that the user entered into the form:

                                  $query = new CGI;

$filename = $query->param("photograph");
$email_address = $query->param("email_address");

Some browsers pass the whole path to the file, instead of just the filename, so it'southward a practiced thought to strip off everything that includes backslashes (Windows browsers) and forward slashes (Unix browsers) and which might appear before the filename:

                                  $filename =~ s/.*[\/\\](.*)/$1/;              

4. Getting the File Handle

Every bit I mentioned above, we tin use the upload() method to grab the file handle of the uploaded file (which actually points to a temporary file created by CGI.pm). We do this equally follows:

                                  $upload_filehandle = $query->upload("photo");              

5. Saving the File

Now that we have a handle to our uploaded file, we can read its contents and relieve information technology out to a new file in our file upload expanse. Nosotros'll use the uploaded file's filename as the name of our new file:

                                  open UPLOADFILE, ">$upload_dir/$filename";

while ( <$upload_filehandle> )
{
print UPLOADFILE;
}

shut UPLOADFILE;

half dozen. Thank the User

We've now uploaded our file! The last pace is to brandish a quick thank-you note to the user, and to evidence them their uploaded photo and email accost:

                                  impress $query->header ( );
print <<END_HTML;

<HTML>
<HEAD>
<Title>Cheers!</Title>
</Caput>

<Torso>

<P>Thanks for uploading your photograph!</P>
<P>Your email address: $email_address</P>
<P>Your photo:</P>
<img src="/upload/$filename" edge="0">

</BODY>
</HTML>

END_HTML

The Finished Script

Your finished CGI script should look something similar this:

                                  #!/usr/bin/perl -w

employ CGI;

$upload_dir = "/home/mywebsite/htdocs/upload";

$query = new CGI;

$filename = $query->param("photo");
$email_address = $query->param("email_address");
$filename =~ due south/.*[\/\\](.*)/$i/;
$upload_filehandle = $query->upload("photo");

open UPLOADFILE, ">$upload_dir/$filename";

while ( <$upload_filehandle> )
{
print UPLOADFILE;
}

close UPLOADFILE;

impress $query->header ( );
print <<END_HTML;

<HTML>
<HEAD>
<TITLE>Thank you!</TITLE>
</Caput>

<Body>

<P>Thanks for uploading your photo!</P>
<P>Your e-mail accost: $email_address</P>
<P>Your photo:</P>
<img src="/upload/$filename" border="0">

</Torso>
</HTML>

END_HTML

Save this file on your hard drive, and call it "upload.cgi".

Now we've created our server-side script, nosotros can place both the script and the form on our server and exam the file upload.

Putting It All Together

1. Place the Files on your Server

Place the HTML form somewhere under your Website's document root, and your CGI script in your Website'due south cgi-bin directory.

Note: don't forget to make the CGI script executable if you lot're on a UNIX server - chmod a+rx upload.cgi or chmod 755 upload.cgi

2. Prepare the Correct Paths and URLs

If necessary, change the "upload.cgi" URL in the <FORM> tag to signal to the right URL for the CGI script:

                                  <Form Activeness="/cgi-bin/upload.cgi" METHOD="mail service"                  
ENCTYPE="multipart/form-data">

Also, don't forget to set the right path to Perl in your CGI script, and the correct accented path to the 'upload' directory that you created on your server:

                                  #!/usr/bin/perl -westward
$upload_dir = "/home/mywebsite/htdocs/upload";

iii. Test the Script

Permit'due south try it out! Go to the URL of your file upload form on your server, select a photograph to upload, and enter your email address:

474uploadform

Press the "Submit Class" button. If all goes well, the photo will be uploaded to the server, and you should run across the "Thanks!" page, which also displays your photo and email address:

474thanksscreen

Congratulations - y'all've written a file upload handler script!

If you become Internal Server Errors, double-check the permissions, paths and URLs described above, and look for other mutual CGI script pitfalls. For instance, editing a file on Windows and and then uploading it to your Web server in Binary format will cause the script to crash on Unix servers.


Final Thoughts

A couple of points almost this script are worth a mention:

If you were doing this on a existent Website with lots of users, it would exist a good thought to create a separate upload directory for each user, so that one user's photograph won't be overwritten with another user's photo of the same name!

File upload isn't perfect. All browsers handle file uploads slightly differently, and some browsers can accept trouble uploading files to certain types of servers and scripts. On the whole, though, almost users won't have whatsoever problem with the nigh pop browsers.

That's it. Have fun with your file uploads!

wardoribirlead.blogspot.com

Source: https://www.filibeto.org/aduritz/misc/web_upload_cgi.html

Related Posts

0 Response to "How to Upload Files From Html Form in Perl"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel