2014-07-26 79 views
3

我開始看PSGI了,我知道應用程序的響應應該是數組 ref有三個元素,[code,headers,body]:Perl如何發送zip文件到瀏覽器下載PSGI

#!/usr/bin/perl 

my $app = sub { 
    my $env = shift; 

    return [ 
    200, 
    [ 'Content-type', 'text/plain' ], 
    [ 'Hello world' ], 
    ] 
}; 

問題是如何發送文件,例如zip或pdf下載到瀏覽器。

回答

7

只需設置正確的標題和正文。

my $app = sub { 
    my $env = shift; 

    open my $zip_fh, '<', '/path/to/zip/file' or die $!; 

    return [ 
    200, 
    [ 'Content-type', 'application/zip' ], # Correct content-type 
    $zip_fh, # Body can be a filehandle 
    ] 
}; 

您可能想要嘗試添加其他標頭(特別是「Content-Disposition」)。

+0

很好的答案,我應該在返回響應之前在文件上設置'binmod $ zip_fh;'。 – daliaessam

2

看看perl dancer;它有psgi支持,並且是一個非常輕量級的框架。

例如:

#!/usr/bin/env perl 
use Dancer; 

get '/' => sub { 
    return send_file('/home/someone/foo.zip', system_path => 1); 
}; 

dance; 

運行與 chmod 0755 ./path/to/file.pl; ./path/to/file.pl

電話與:

wget <host>:<port>/

+0

不幸的是我沒有使用任何框架,只需要一個通過PSGI發送文件的原始方法。 – daliaessam

+0

在這種情況下,請嘗試看看這個http://search.cpan.org/~miyagawa/Plack-1.0030/lib/Plack/Response.pm;它表示$ response-> body()可以接受一個文件句柄。 – Blaskovicz

相關問題