From 1556573f29cbf45f76baf3e2efbecb08228741cd Mon Sep 17 00:00:00 2001 From: Quentin Gabriele Date: Tue, 23 Jan 2024 18:21:58 +0100 Subject: [PATCH] fix zipping --- src/MediaZipper.php | 40 ++++++++++++++++++++------ src/Traits/InteractsWithMediaFiles.php | 2 +- 2 files changed, 33 insertions(+), 9 deletions(-) diff --git a/src/MediaZipper.php b/src/MediaZipper.php index 013d065..2247703 100644 --- a/src/MediaZipper.php +++ b/src/MediaZipper.php @@ -7,6 +7,7 @@ use Illuminate\Contracts\Support\Responsable; use Illuminate\Support\Collection; use Symfony\Component\HttpFoundation\StreamedResponse; +use ZipStream\OperationMode; use ZipStream\ZipStream; class MediaZipper implements Responsable @@ -23,10 +24,12 @@ public function toFile(Filesystem $storage, string $path, array $options = []): { $temporaryStream = fopen('php://memory', 'w+'); - $this->getZipStream([ + $zip = $this->getZipStream([ 'outputStream' => $temporaryStream, ]); + $zip->finish(); + $success = $storage->writeStream($path, $temporaryStream, $options); fclose($temporaryStream); @@ -36,10 +39,10 @@ public function toFile(Filesystem $storage, string $path, array $options = []): public function getZipStream(array $options = []) { - $zip = new ZipStream( - ...$this->zipStreamOptions, - ...$options, - ); + $zip = new ZipStream(...array_merge( + $this->zipStreamOptions, + $options + )); /** @var Media $item */ foreach ($this->media as $index => $item) { @@ -56,16 +59,37 @@ public function getZipStream(array $options = []) } } - $zip->finish(); - return $zip; } + public function getSize(): int + { + return (int) $this->media->sum('size'); + } + public function toResponse($request): StreamedResponse { - return new StreamedResponse(fn () => $this->getZipStream(), 200, [ + $simulation = $this->getZipStream([ + 'defaultEnableZeroHeader' => true, + 'sendHttpHeaders' => false, + 'contentType' => 'application/octet-stream', + 'operationMode' => OperationMode::SIMULATE_STRICT, // or SIMULATE_LAX + ]); + + $size = $simulation->finish(); + + return new StreamedResponse(function () { + $zip = $this->getZipStream([ + 'defaultEnableZeroHeader' => true, + 'contentType' => 'application/octet-stream', + ]); + + $zip->finish(); + + }, 200, [ 'Content-Disposition' => "attachment; filename=\"{$this->fileName}\"", 'Content-Type' => 'application/octet-stream', + 'Content-Length' => $size, ]); } } diff --git a/src/Traits/InteractsWithMediaFiles.php b/src/Traits/InteractsWithMediaFiles.php index e2074d4..f168cd1 100644 --- a/src/Traits/InteractsWithMediaFiles.php +++ b/src/Traits/InteractsWithMediaFiles.php @@ -17,7 +17,7 @@ /** * @property ?string $disk * @property ?string $path - * @property ?int $size + * @property ?int $size The filesize in bytes * @property ?float $duration in miliseconds */ trait InteractsWithMediaFiles