daliaessam
daliaessam

Reputation: 1656

Perl how to send zip file to browser for download in 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.

Upvotes: 4

Views: 860

Answers (2)

Dave Cross
Dave Cross

Reputation: 69244

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').

Upvotes: 10

Blaskovicz
Blaskovicz

Reputation: 6160

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>/

Upvotes: 2

Related Questions