Skip to content

Instantly share code, notes, and snippets.

@bimmerlabs bimmerlabs/myapp.pl
Last active Jan 11, 2018

Embed
What would you like to do?
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
You can’t perform that action at this time.