【问题标题】:How to post the content of a file using Perl Script如何使用 Perl 脚本发布文件的内容
【发布时间】:2018-02-15 22:35:52
【问题描述】:

我对 Perl 很陌生,非常需要帮助。 我有一个 file.txt,我想将其内容发布到网络服务 url。

这是我的 file.txt 内容的示例。

姓名:姓名1 地址:地址1 姓名:姓名2 地址:地址2 姓名:姓名3 地址:地址3

这里是我的 post.pl(来自此站点的引用: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";
   }

使用上面的文件和脚本,我怎样才能发布文件的内容。 提前谢谢你。

【问题讨论】:

    标签: perl post


    【解决方案1】:

    您可以使用LWP::UserAgent 中的post() 方法来简化此操作。在下面,它使用来自HTTP::Request::CommonPOST() 方法,因此您可以在此处查看有关它如何处理文件上传的更多详细信息。

    #!/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 会为您完成。

    【讨论】:

    • 如果您将文件的内容作为二进制数据上传到变量中怎么办? (例如,您从数据库中获取数据)我无法找到告诉 UserAgent 将其作为文件内容发送的方法,它作为一个字段的字符串发送,服务器不是作为附件接收,而是作为字段值。
    • @FranciscoZarabozo:这听起来像是你应该作为一个新问题发布的内容。
    【解决方案2】:

    从如下文件中读取内容。

    use strict;
    use warnings;
    use utf8;
    
    open my $fh, '<', '/path/to/file.json' or die "failed to open: $!";
    my $content = do { local $/; <$fh> };
    close $fh;
    

    或者

    use File::Slurp;
    my $content = read_file('/path/to/file.json');
    

    【讨论】:

      【解决方案3】:

      好的,首先,我想说的是您的 file.txt 的格式不是很直观的格式,因为它不是任何标准化格式,所以我们不能只调用执行 CSV 的通用库或 JSON 解析。无论如何,您本质上需要的是在两者之间构建一个解析函数。

      sub parse_file {
          my ($filename) = @_;
      
          open(FILE, $filename) or die sprintf ("Could not open '%s' (%s)", $filename, $!));
      
          my $string = '';
          my @args;
      
          foreach my $line (<FILE>) {
              chomp($line);
      
              # Assumes that every record is separated by a blank line.
              if ($line) {
                  my ($keyname, $value) = split(':', $line);
      
                  # Remove empty spaces left and right
                  $keyname =~ s/^\s+|\s+$//g;
                  $value =~ s/^\s+|\s+$//g;
      
                  $string = ($string)
                      ? $string.', '.sprintf('"%s":"%s"', $keyname, $value);
                      : sprintf('"%s":"%s"', $keyname, $value);
              }
              else {
                  # When we have a blank line, store the string we have concatenated.
                  push (@args, sprintf("{%s}", $string);
                  $string = ''; # Reset the string for the next record
              }
          }
      
          close(FILE) or die sprintf ("Could not close '%s' (%s)", $filename, $!));
      
          return (wantarray) ? @args : \@args;
      }
      

      从这个函数返回的参数,你可以去

      my @post_args = parse_file($path_to_your_file);
      foreach my $post_arguments (@post_args) {
          # Call your HTTP request to set post_arguments and post the form
      }
      

      【讨论】:

      • 不确定您为什么担心解析文件。所有问题都是如何将文件发布到 Web 服务。由远程 Web 服务来处理解析文件并用它做一些有用的事情:-)
      猜你喜欢
      • 2012-07-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-04
      • 2014-05-15
      • 2011-02-07
      • 2018-07-20
      • 2016-12-23
      • 1970-01-01
      相关资源
      最近更新 更多