perlpsgi

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.


Solution

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