I've a form that allow the customer to download every photos that a photograph uploaded before. Here is my submit form :

 public function submitForm(array &$form, FormStateInterface $form_state)
    $parameters = \Drupal::routeMatch()->getParameters();
    $shooting = Node::load($parameters->get('shooting_id'));

    $destination = \Drupal::service('file_system')->realpath('temporary://');

    $zipname = $destination . '/vos_photos_'.$shooting->id().'.zip';

    header('Content-Type: application/zip');
    header('Content-disposition: attachment; filename='.$zipname);
    header('Content-Length: ' . filesize($zipname));

    $zip = new \ZipArchive();

    $zip->open($zipname, constant("ZipArchive::CREATE"));

    foreach ($shooting->field_shooting_photos as $media) {

      $uri = $media->entity->field_media_image->entity->uri->value;
      $file_path = \Drupal::service('file_system')->realpath($uri);

      // Ajout de chaque fichier dans le zip //
      $zip->addFile($file_path, $media->entity->field_media_image->entity->name);





This works great.
The only problem is when I unzip it, I get var/www/drupalvm/web/sites/defaults/files/{My content}
I would like to just have a simple folder files/{my content} without the long path before, or if it's not possible, simply {my content} when you extract the zip. Thank you
I'm pretty the problem can be solved in the addFile by giving a localname, I just can't figure out how to


I finally found the solution, instead of

$zip->addFile($file_path, $media->entity->field_media_image->entity->name);

I simply put

$zip->addFile($file_path, basename($file_path));

and it does the job.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.