2

I'm currently trying to upload multiple image files using a single form (AJAX) and the Bulletproof library.

I managed to get 1 working, the #avatar-upload-input successfully uploads images through the AJAX form.

<form method="post" action="ajax/updateprofile" enctype="multipart/form-data" id="dynamicform" data-func="updateprofile">
     <input type="file" name="avatar" id="avatar-upload-input" accept="image/*"/>
     <input type="file" name="banner" id="banner-upload-input" accept="image/*"/>
</form>

Now I'm trying to get the second one working, but I'm really not sure how I would go and get that working!

I googled it and saw that more people were having the same question, but none really got a clear answer.

It was suggested in the comments of these issues that a loop is needed on $_FILES. I have tried the following:

foreach($_FILES as $file) {
    $image = new Bulletproof\Image($file);
    $image->setName($Hashids->encode($_SESSION['user_id']) . '-' . uniqid()); 
    $image->setMime(array('jpg', 'png', 'jpeg'));
    $image->setLocation('../assets/images/usercontent/pfp');

    if($image['avatar']){
        $upload_pfp = $image->upload(); 

        bulletproof\utils\resize($upload_pfp->getFullPath(), $upload_pfp->getMime(), $upload_pfp->getWidth(), $upload_pfp->getHeight(), 190, 175);
    }
}

That didn't gave me any errors but also didn't upload any image.

I hope someone can help me solve how can I upload multiple images using the mentioned library!

Appel Flap
  • 261
  • 3
  • 23
  • I think this is one of the issues `if($image['avatar'])`. Since you're iterating through the array, you won't get the `avatar`-key. Try and change `foreach($_FILES as $file) {` to `foreach($_FILES as $key => $file) {` and then instantiate the class with: `$image = new Bulletproof\Image([$key => $file]);` – M. Eriksson Oct 03 '18 at 21:28

1 Answers1

3
foreach($_FILES as $key => $file) { //get upload name: $key
  $image = new Bulletproof\Image($file);
  $image->setName($Hashids->encode($_SESSION['user_id']) . '-' . uniqid()); 
  $image->setMime(array('jpg', 'png', 'jpeg'));
  $image->setLocation('../assets/images/usercontent/pfp');

  if($key == 'avatar'){             //which file
    if($image->upload()){           //upload succeed?
      bulletproof\utils\resize(     //you are still playing with $image
        $image->getFullPath(), 
        $image->getMime(), 
        $image->getWidth(), 
        $image->getHeight(), 
        190,
        175
      );
    }
  }elseif($key == 'banner'){        //do it all over again with banner
    if($image->upload()) {
      //do something with banner
    }
  }
}
Sven Liivak
  • 1,323
  • 9
  • 10