4

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.

daliaessam
  • 1,636
  • 2
  • 21
  • 43

2 Answers2

10

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

Dave Cross
  • 68,119
  • 3
  • 51
  • 97
2

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

Blaskovicz
  • 6,122
  • 7
  • 41
  • 50
  • 1
    unfortunately I am not using any frameworks, just need a raw method to send the file through PSGI. – daliaessam Jul 26 '14 at 01:39
  • In that case, try taking a look at this http://search.cpan.org/~miyagawa/Plack-1.0030/lib/Plack/Response.pm; it says that $response->body() can take a file handle. – Blaskovicz Jul 26 '14 at 01:47