O'Reilly logo

Perl & LWP by Sean M. Burke

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

File Uploads

So far we've discussed users entering text data that they type (or paste) into forms. But there's another way to submit data: with a type=file form element, which allows users to select a file on their local systems to upload when the form is submitted.

Currently, three things have to happen for a user to upload a file via a form. First, the program that will be processing the form has to be expecting a file to be uploaded (you can't just alter the HTML for any form and stick a type=file field into it). Second, the form has to have an <input type= file name= whatever > element. And third, the form element has to have its attributes set like so:

<form method=post enctype="multipart/form-data" action="url">

This is necessary because file-upload fields can't be conveyed by the normal form-data encoding system, but instead have to use the "multipart/form-data" encoding system (which, incidentally, can be conveyed only across POST requests, not across GET requests).

Suppose, for example, that you were automating interaction with an HTML form that looked like this:

<form enctype="multipart/form-data" method=post
  action="http://pastel.int/feedback.pl">
Subject:               <input name="subject" type="text">
<br>File to process -- <input name="saywhat" type="file">
<br>Your Name --       <input name="user"    type="text">
<input type="submit" value="Send!"></form>

Modeling the first and third fields is as we've seen before -- a simple matter of $browser->post($url, ['subject'=>..., 'user'=>...]) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required