Uploading Multiple Files

I’m trying to upload multiple files in one go, which is then restricted by how many I’ve set in the blueprint, if that’s possible? but it only seems to just upload one.

// Upload the images
    $count_files = 0;
if (!empty($_FILES['file']['name'])) {
  $count_files = count($_FILES['file']['name']);
}
    do {
      try {
        $upload = new Upload($p->root() . DS . '{safeFilename}', array('input' => 'file', 'index' => $index));
        $index++;
      } catch(Error $e) {
        switch($e->getCode()) {
          case Upload::ERROR_MISSING_FILE:
            // No more files have been uploaded
            $missingFile = true;
            break;
          // See the Upload class for other error values
        }
      }
    } while ($index < $count_files && !$missingFile);
    
    // Check if an image has been uploaded at all
    if($index === 0) {
      $error = 'No file uploaded.';
    }
  }

Not sure what I’m doing wrong.

input type="file" name="file[]" accept="image/*" multiple

Any assistance will be greatly appreciated.

Have a look at this thread here: Problem sending images to the creation of a page (front end)

I think what is missing in your code is the declaration of the $missingFile variable? It should be set to false at the beginning…

1 Like

Used the code in the link suggested texnixe, brilliant thank you! I assume in the array you can specify the max amount of files you can upload? I can’t find the variable for this however.

There is no way to limit the amount of files a user can upload via some setting in the form. You could use JavaScript to do this on the client side; additionally, you always have to check this on the server side as well.

Since $count_files = count($_FILES['file']['name']);gives you the number of files, you can act on this and either tell the user off (hey, you can only upload 5 files) or stop uploading after x files.

if($count_files > $max_allowed_files) {
  // go away
} else {
  // try uploading
}

I don’t know where you want to set this limit, but the blueprint is not the right place, because the frontend has nothing to do with blueprints (yes, I know there are plugins that allow you to read blueprint information, but that would be overkill).

1 Like

Thanks texnixe, I’ll try those methods. I guess another fix would be just X amount of upload inputs.

Yes, that would be an alternative.