Skip to content

Instantly share code, notes, and snippets.

@bimmerlabs
Last active January 11, 2018 16:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bimmerlabs/70460319be1c4aa235046ed6399f57f8 to your computer and use it in GitHub Desktop.
Save bimmerlabs/70460319be1c4aa235046ed6399f57f8 to your computer and use it in GitHub Desktop.
A Mojolicious::Lite forZip file streaming with Mojo::Asset::Memory
#!/usr/bin/env perl
use Mojolicious::Lite;
use Archive::Zip::SimpleZip qw($SimpleZipError);
get '/#file' => sub {
my $c = shift;
# read a file from disk
my $file1 =
Mojo::Asset::File->new(
path => '/path/to/' . $c->param('file')
);
# generate one on the fly
my @file2 = (
"this\n",
"is\n",
"a\n",
"test\n"
);
my $file2 = Mojo::Asset::Memory->new;
foreach my $line (@file2) {
$file2->add_chunk($line);
}
my $zipfile;
my $zip = Archive::Zip::SimpleZip->new(\$zipfile)
or die "Cannot create zip file: $SimpleZipError\n" ;
$zip->addString( $file1->slurp, Name => $c->param('file') );
$zip->addString( $file2->slurp, Name => 'test.txt' );
$zip->close();
# stream zip file with Mojo::Asset::Memory
$c->res->headers->content_disposition(
'attachment; filename=' . $c->param('file') . '.zip;');
$c->res->headers->content_type('application/zip');
$c->reply->asset(Mojo::Asset::Memory->new->add_chunk(
$zipfile
));
};
app->start;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment