Perl CGI 下载文件

Perl CGI download file

我需要创建一个 HTML 文件来输入文本或文件。在处理和下载文件的同时处理和打印文本。

我无法创建下载。我尝试下载 header,但没有成功。处理文件后,将使用 @array 创建一个新文件。 output_file.txt 用户应该可以下载。

#!C:/perl64/bin/perl.exe
use strict;
use warnings;
use CGI::Pretty qw(:all);


# HTML
print header();
print start_html();
print start_form();
print textfield('text');
print (submit);
print filefield('file');
print submit();
print end_form();
print end_html();

if (param ('file')) {
    my $fh = param('file');
# File processed to get @result and made new file
    open (OUT, ">output/output_file.txt");
    print OUT @result;
# Need to download output_file.txt file
}

# Text processed and printed
elsif(param('text')){
    my $text = param('text')
}

尝试以下操作:

#!/usr/bin/perl -w
use strict;
use warnings;
use CGI::Pretty qw(:all);
my @result;
if (param ('file')) {
    my $file_name=param('file');
    my $file_handle =upload('file');
    my $file_size=-s $file_handle;
    print header(
        -type=>'application/octet-stream',         
        -attachment=> $file_name,
        -Content_Length=>$file_size
    );
# file processed to get @result and made new file 
    binmode($file_handle);
    while (<$file_handle>){
        print $_;
        push (@result,$_);
    }
# need to download output_file.txt file
}
# text processed and printed
elsif(param('text')){
    my $text = param('text');
    print header(
        -type=>'application/octet-stream',         
        -attachment=> "Sample.txt",
        -Content_Length=>length($text)
    );
    print $text;
}

# html 
print header();
print start_html();
print start_form();
print textfield('text');
print (submit);
print end_form();
print start_form();
print filefield('file');
print submit();
print end_form();
print end_html();

这是我修改过的例子:

#!C:\Program Files\perl\bin\perl.exe

use CGI ':standard';  
use CGI::Carp qw ( fatalsToBrowser );  

$input_val = $ENV{'QUERY_STRING'};

($field_name, $command) = split (/=/, $input_val);
($file_name, $option_name) = split(/&/, $command);


$file_path= "Database/$file_name";

$directorypath = "Database/";

my $files_location;  
my @fileholder;  

$files_location = $directorypath;  

if ($file_name eq '')
{  
    print "Content-type: text/html\n\n";  
    print "File doesn't exist";  
} else {  

    open(DLFILE, "<$files_location/$file_name") || Error('open', 'file');  
    @fileholder = <DLFILE>;  
    close (DLFILE) || Error ('close', 'file');  

    print "Content-Type:application/x-download\n";  
    print "Content-Disposition:attachment;filename=$file_name\n\n";  
    print @fileholder;  
}

print "</HTML>";
exit 0;

参考这个网站:http://www.perlnotes.com/study0680.htm