簡體   English   中英

在Perl中哪些文件上傳頭?

[英]Which headers for file upload in Perl?

我已經堅持了好幾個小時,但一直無法通過研究找到解決方案。

以下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);

如果有人能指出它不起作用的原因,我將不勝感激。 謝謝!

您提供的是text/plain的Content-Type,這顯然是錯誤的-您需要發送包含text/plain附件的multipart/form-data MIME消息。 可以使用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; 您的代碼。

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',
   ],
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM