Last active
January 11, 2018 16:54
-
-
Save bimmerlabs/70460319be1c4aa235046ed6399f57f8 to your computer and use it in GitHub Desktop.
A Mojolicious::Lite forZip file streaming with Mojo::Asset::Memory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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