0

I am making an external API call which returns several objects with download URL inside. Those are all PDF-s of which I would like to provide a single ZIP download link.

The way it works now is that I am downloading every single PDF to a specific user folder, and then making a ZIP out of it and presenting it back to user.

I see this as a somewhat slow and inefficient of doing things as the user will have to trigger another download for the ZIP, and this way I am making user wait basically for 2 downloads of the same file batch.

Is there a smarter way to deal with this?

$path = '/user_downloads/' . Auth::user()->id . '/';

if (!Storage::disk('uploads')->has($path)) {
    Storage::disk('uploads')->makeDirectory($path);
}

$zipper = new \Chumper\Zipper\Zipper;
$zip_filename = 'zipped/' . uniqid() . '_merged.zip';
foreach (json_decode($res)->hits as $hit) {
    $filename = public_path() . $path . uniqid() . '_file.pdf';
    copy($hit->document_download_link, $filename);
    $zipper->make($zip_filename)->add($filename);
}
Norgul
  • 4,613
  • 13
  • 61
  • 144

2 Answers2

1

This question has a couple of ways you could present the files to the user on by one but this is less user friendly and might get blocked by browsers.

You could probably also use JSZip (haven't looked too closely at it) but that would use the browser's RAM to compress the PDF's which is not ideal, especially on mobile devices.

I think your current solution is the best one.

Thomas
  • 8,426
  • 1
  • 25
  • 49
  • I am using this package https://github.com/Chumper/Zipper and it works great. I was wondering about the approach only. Updated the answer with code. Thanks for the insight – Norgul Jul 09 '17 at 09:45
1

The add method can receive an array of files, so, I would create the array of files inside the foreach and when finished, create the zip:

foreach (json_decode($res)->hits as $hit) {
copy($hit->document_download_link, $filename);
$files[] = public_path() . $path . uniqid() . '_file.pdf';
}

 $zipper->make($zip_filename)->add($files);
Aarón Gutiérrez
  • 1,400
  • 3
  • 16
  • 41