Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl how to send zip file to browser for download in PSGI

Tags:

perl

psgi

I am started to look at the PSGI, I know the response from the application should be an array ref of three elements, [code, headers, body]:

#!/usr/bin/perl

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

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

The question is how to send a file for example zip or pdf for download to the browser.

like image 461
daliaessam Avatar asked Sep 21 '25 02:09

daliaessam


2 Answers

Just set the correct headers and body.

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
  ]
};

You might want to experiment with adding other headers (particularly 'Content-Disposition').

like image 118
Dave Cross Avatar answered Sep 23 '25 07:09

Dave Cross


Take a look at perl dancer; it has psgi support and is a very lightweight framework.

example:

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

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

 dance;

run with chmod 0755 ./path/to/file.pl; ./path/to/file.pl

call with:

wget <host>:<port>/

like image 34
Blaskovicz Avatar answered Sep 23 '25 08:09

Blaskovicz