Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PERL CGI支持多种内容类型。如何下载文件和查看内容。_Perl_Cgi - Fatal编程技术网

PERL CGI支持多种内容类型。如何下载文件和查看内容。

PERL CGI支持多种内容类型。如何下载文件和查看内容。,perl,cgi,Perl,Cgi,打印文件(在服务器上)内容并提供直接下载链接的页面 Download File HERE Start contents of file: line 1 line 2 line 3 ... 我不知道最好的方式和正确的标题,将允许下载链接和HTML文本。这张照片是空白的 print $mycgi->header( -cookie => $mycookie, -Type =>

打印文件(在服务器上)内容并提供直接下载链接的页面

Download File HERE

Start contents of file:
line 1
line 2
line 3
...
我不知道最好的方式和正确的标题,将允许下载链接和HTML文本。这张照片是空白的

            print $mycgi->header(
                   -cookie => $mycookie, 
                    -Type => "application/x-download"
                    -'Content-Disposition'=>'attachment; filename="FileName"'
              );

您可以包含指向脚本的链接,并将文件名作为参数传递。链接可能如下所示:

http://url/to/script?action=download&file=foo
在下面,只需打印文件的内容:

#!/usr/bin/perl -T

use strict;
use warnings;

use CGI qw/escapeHTML/;

my $q = CGI->new;

print $q->header,
      $q->start_html('foo'),
      $q->a({ -href => 'http://url/to/script?action=download&file=foo' }, 'Click to download'),
      "<pre>";

open my $fh, "<", "/path/to/file" or die $!;

print escapeHTML($_) while <$fh>;

close $fh;

print "</pre>", $q->end_html;

请注意,您还需要在响应正文中打印文件的内容。

您太棒了。非常感谢。污点中的正则表达式在做什么?每当您使用CGI外部的数据(输入参数、环境变量等)时,您应该对它们进行清理(并使用
-T
标志打开污点模式强制您进行清理)。一种方法是创建一个可接受字符的白名单,这就是正则表达式所做的<代码>操作可以合理地限制为仅使用字母数字字符,而在文件名中允许使用
-
。您可以更改这些正则表达式以适合您的应用程序,但目标是过滤掉危险字符,如
|
$
my $q = CGI->new;

# Untaint parameters
my ($action) = ($q->param('action') =~ /^(\w+)$/g);
my ($file)   = ($q->param('file') =~ /^([-.\w]+)$/g);

# Map file parameter to the actual file name on your filesystem.
# The user should never know the actual file name. There are many
# ways you could implement this.
???

if ($action eq "download") {
    print $q->header(
        -type => "application/x-download",
        -'Content-Disposition' => 'attachment; filename="FileName"'
    );

    open my $fh, "<", $file or die "Failed to open `$file' for reading: $!";

    print while <$fh>;

    close $fh;
}