phplaravelzipzipstream

Laravel Zipstream add file from stream


I'm trying to get ZipStream working in Laravel 5.4. I want to stream files from s3 to create a ZipStream which is returned to the browser.

Currently my code produces corrupt ZIP files the same size as valid ZIP files.

This is my action method:

public function mediaZip(User $user)
{
    return response()->stream(function () use ($user) {
        $zip = new ZipStream($user->name . ".zip", [
            'content_type' => 'application/octet-stream'
        ]);

        foreach ($user->media as $medium) {
            $stream = Storage::disk("s3")->readStream($medium->location);
            $zip->addFileFromStream($medium->name, $stream);
        }

        $zip->finish();
    });
}

If I read each file into memory using the code below, the ZIP files work fine. This is however undesirable as I will be working with files that can be several gigabytes large.

public function mediaZip(User $user)
{
    return response()->stream(function () use ($user) {
        $zip = new ZipStream($user->name . ".zip", [
            'content_type' => 'application/octet-stream'
        ]);

        foreach ($user->media as $medium) {
            $file = Storage::disk("s3")->read($medium->location);
            $zip->addFile($medium->name, $file);
        }

        $zip->finish();
    });
}

Can anyone help me figure out what's going wrong with the ZIP files?

Thanks!


Solution

  • Got it to work by specifying "store" for the storage_method param.

    $zip->addFile($medium->name, $file, [], "store");