Perl WWW :: Mechanize :: Firefox和输入类型文件

时间:2012-07-11 10:43:41

标签: perl mechanize www-mechanize

交叉发布http://perlmonks.org/?node_id=981067

使用WWW :: Mechanize :: Firefox将文件上传到带有使用输入类型文件的表单的网站时遇到问题,如下所示:

<form enctype="multipart/form-data" action="uploader.php" method="POST" id="formular">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload: <input name="image0" type="file" id="image0"/><br />
<input type="submit" value="Upload File" />

uploader.php的内容如下:

<?php
$target_path = "uploads/";

$target_path = $target_path . basename( $_FILES['image0']['name']); 

if(move_uploaded_file($_FILES['image0']['tmp_name'], $target_path)) {
    echo "The file ".  basename( $_FILES['image0']['name']). 
    " has been uploaded";
} else{
    echo "There was an error uploading the file,".  basename( $_FILES['image0']['name'])." please try again!";
}
?>

我用来上传文件的代码如下:

#!/usr/bin/perl
use strict;
use warnings;
use WWW::Mechanize::Firefox;

my $bot = WWW::Mechanize::Firefox->new( autoclose => 0,activate =>1);

$bot->get('http://127.0.0.1/file/index.html');
$bot->form_id('formular');
$bot->field('image0','IMAGE.JPG');
$bot->submit;

执行时没有错误,表单被提交但在image0中没有任何内容。

我使用的WWW :: Mechanize :: Firefox的版本是0.66我的perl版本是:为MSWin32-x86-multi-thread构建的v5.10.0

由于

1 个答案:

答案 0 :(得分:1)

为什么不尝试在field()方法中添加整个路径到图像文件和键/值对,如

my $image_path = "/home/images/IMAGE.JPG";
$bot->field(image0=>$image_path);
$bot->submit();

此外,假设WWW::Mechanize::Firefox继承了所有LWP::UserAgents方法,请在$bot->submit();

之前包含以下代码
$bot->add_handler("request_send",  sub { shift->dump; return });
$bot->add_handler("response_done", sub { shift->dump; return });

这将启用您的代码登录。密切关注日志文件中的请求和响应代码,例如“HTTP 200 OK”或“HTTP 302 Found”。这些是标准的HTTP响应代码,因此您将知道您正在获得正确的响应。