Thursday, December 10, 2009

WWW::Mechanize for uploading files

The WWW::Mechanize::Cookbook doesn't have an example program for file uploads. So - if you need to quickly upload a file to a server with Perl - here's how you do it:

Please let me know if you have any feedback on this example.

8 comments:

  1. It would probably be a good idea to submit this example as a patch to WWW::Mechanize::Cookbook so that anyone who looks for it going forward will find it where you looked :)

    ReplyDelete
  2. Anonymous: Yes, definitely! I needed to write this down for a friend (a PHP sufferer who must needs be enlightened ;), and so figured I'd post it for comments. Hopefully I'll review it and send a patch - or fork-and-fix, if GitPAN catches up to WWW::* by this weekend!

    ReplyDelete
  3. Hallo is this right? "new WWW::Mechanize"
    It looks like php.
    A friend of mine said Obj. in Perl are generated
    with "WWW::Mechanize->new"

    ReplyDelete
  4. Anonymous: Yup, it's Perl all right. `Class::Name->new` *is* the recommended usage, but I prefer `new Class::Name` - creating a new object is magical enough that I think it should be visually distinct from any other object/class call. I can see why it would be confusing though, and if you prefer `Class::Name->new`, that works perfectly as well.

    ReplyDelete
  5. I agree that this should be part of the Cookbook.

    I should note that this example works because WWW::Mechanize is a subclass of LWP::UserAgent, and 'post' is a method of the latter.

    Sean Burke's Perl & LWP, pages 81-4, explains this example along with some embellishments.

    ReplyDelete
  6. It is worth noting that mechanize can upload files using the normal field() and click() methods. If the html includes a tag <input type=file name=test>, then mechanize can upload /home/me/filetoupload this way:

    $mech->field('test','/home/me/filetoupload');
    $mech->click('submit');

    ReplyDelete