如何使用Perl脚本发布文件的内容 [英] How to post the content of a file using Perl Script
问题描述
我对Perl非常陌生,非常需要帮助. 我有一个file.txt文件,我想在其中将其内容发布到Web服务URL.
I am very new to Perl and badly needing for help. I have a file.txt where I want to post its content to a webservice url.
这是我的file.txt内容的示例.
This is the sample of my file.txt content.
Name: name1
Address: address1
Name: name2
Address: address2
Name: name3
Address: address3
And here it my post.pl (referencing from this site: http://xmodulo.com/how-to-send-http-get-or-post-request-in-perl.html)
#!/usr/bin/perl
use warnings;
use strict;
use LWP::UserAgent;
my $ua = LWP::UserAgent->new;
my $url = "https://domain/post.php";
# set custom HTTP request header fields
my $req = HTTP::Request->new(POST => $url);
$req->content_type('application/json');
# add POST data to HTTP request body
my $post_data = '{"name":"myName", "address":"myAddress"}'; // I want to post here the content of file.txt
$req->content($post_data);
print $req->as_string;
my $resp = $ua->request($req);
if ($resp->is_success) {
my $message = $resp->decoded_content;
print "\nReceived reply: $message\n";
}
else {
print "HTTP POST error code: ", $resp->code, "\n";
print "HTTP POST error message: ", $resp->message, "\n";
}
使用上述文件和脚本,如何发布文件内容. 预先谢谢你.
Using above file and script, how can I possible post the contents of the file. Thank you in advance.
推荐答案
您可以从 HTTP :: Request :: Common POST()方法. >,因此您可以在此处查看有关它如何处理文件上传的更多详细信息.
You can use the post()
method from LWP::UserAgent to make this much simpler. Underneath, it uses the POST()
method from HTTP::Request::Common, so you can look there for more details about how it handles file uploads.
#!/usr/bin/perl
use warnings;
use strict;
use LWP::UserAgent;
my $ua = LWP::UserAgent->new;
my $url = 'https://domain/post.php';
# The name of the file input field on the HTML form/
# You'll need to change this to whatever the correct name is.
my $file_input = 'file-input';
# Path to the local file that you want to upload
my $file_path = '/path/to/some/file';
my $req = $ua->post($url,
Content_Type => 'form-data',
Content => [
$file_input => [ $file_path ],
],
);
您甚至不需要自己打开文件-HTTP :: Request :: Common会为您完成该操作.
You don't even need to open the file yourself - HTTP::Request::Common does that for you.
这篇关于如何使用Perl脚本发布文件的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!