Perl CGI下载文件

时间:2015-07-27 20:48:37

标签: perl download cgi

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

我无法创建下载。我尝试使用下载标题,但它没有用。处理完文件后,将使用@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')
}

2 个答案:

答案 0 :(得分:0)

尝试以下方法:

#!/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();

答案 1 :(得分:0)

这是我修改过的一个例子:

#!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