Perl中的文件上传哪些标题?

时间:2012-11-11 06:07:55

标签: perl file upload header

我已经被困在这几个小时了,我无法通过研究找到解决方案。

以下HTML代码可以满足我的要求:

<form action="uploader.php" method="POST" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="Filedata" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>

但是,以下Perl代码不起作用。我认为这是因为我没有发送所需的标题。

my @headers  = ('Content-Disposition' => 'form-data; name="Filedata"; filename="test.txt"',
                'Content-Type'        => 'text/plain',
                'Content'             => 'File content goes here.');

my $browser  = LWP::UserAgent->new;
my $response = $browser->post('uploader.php', undef, @headers);

如果有人能指出它不起作用的原因,我将不胜感激。 谢谢!

2 个答案:

答案 0 :(得分:7)

您提供的内容类型为text/plain,这显然是错误的 - 您需要发送multipart/form-data MIME邮件,并将该文件作为text/plain附件发送。您可以手动使用MIME模块执行此操作,但正如jpalecek指出的那样,HTTP::Request::Common已经知道如何为您执行此操作。这样的请求应该有效:

my $response = $browser->request(
    POST "http://somewhere/uploader.php",
        Content_Type => 'form-data',
        Content => [
            Filedata => [ 
                undef,
                "test.txt",
                Content_Type => "text/plain",
                Content => "file content goes here"
            ]
        ]
);

或者,如果test.txt实际存在于磁盘上:

my $response = $browser->request(
    POST "http://somewhere/uploader.php",
        Content_Type => 'form-data',
        Content => [
            Filedata => [ "/path/to/test.txt" ]
        ]
);

就够了。无论哪种情况,只需确保将use HTTP::Request::Common;添加到您的代码中。

答案 1 :(得分:4)

my $response = $ua->post('http://.../uploader.php',
   Content_Type => 'form-data',
   Content => [
      Filedata => [ undef, 'test.txt',
         Content_Type => 'text/plain',
         Content      => "Hello, World!\n",
      ],
      submit => 'Submit',
   ],
);

->post的参数与HTTP::Request::CommonPOST子广告的参数相同。

如果您真正想要这样做,它还能够从磁盘读取文件。

my $response = $ua->post('http://.../uploader.php',
   Content_Type => 'form-data',
   Content => [
      Filedata => [ 'test.txt', 'test.txt',
         Content_Type => 'text/plain',
      ],
      submit => 'Submit',
   ],
);