Magento – Upload Multiple Images on the frontend Form

frontendimage-uploadmagento2

I want to upload Multiple images on frontend side. i have added

enctype and Input type file

the field is accepting multiple images but after printing array of Data its shows only one single image.

Frontend form field code is

<div class="control">
            <input type="file" name="images " id="review_field" data-validate="{required:false}" data-bind="value: review().images" multiple title="Upload Product Images" />
        </div>

when I add name="images[]" and after printing the $Data array, the images field doesn't shows. The screenshot is attached with adding images[] in name.
enter image description here

Controller

  /** @var \Magento\Review\Model\Review $review */
        $pathurl = $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) . 'review_booster/';
        $mediaDir = $this->_filesystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath();
        $mediapath = $this->_mediaBaseDirectory = rtrim($mediaDir, '/');
        $files = $this->getRequest()->getFiles();
        if (isset($files['image']) && !empty($files['image']["name"])){
          try {
          $uploader = $this->_fileUploaderFactory->create(['fileId' => 'image']);
          $uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
          $uploader->setAllowRenameFiles(true);
          $path = $mediapath . '/review_module/';
          $data['images'] = $files['image']['name'];
            $result = $uploader->save($path);
          }catch (\Exception $e) {
            $this->messageManager->addError(__($e->getMessage()));
          }
        }

Best Answer

Try below code:

<div class="control">
  <input type="file" name="images[]" id="review_field" data-validate="{required:false}" 
  data-bind="value: review().images" title="Upload 
  Product Images" multiple/>
</div>

<?php
$pathurl = $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) . 'review_booster/';
$mediaDir = $this->_filesystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath();
$mediapath = $this->_mediaBaseDirectory = rtrim($mediaDir, '/');
//$files = $this->getRequest()->getFiles(); 
$images = $this->getRequest()->getFiles('images');
if(count($files)){
  $i = 0;
  foreach ($images as $files) {
    if (isset($files['tmp_name']) && strlen($files['tmp_name']) > 0) {
      try {
        $uploader = $this->_fileUploaderFactory->create(['fileId' => $images[$i]]);
        $uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
        $uploader->setAllowRenameFiles(true);
        $path = $mediapath . '/review_module/';
        $data['images'] = $files['name'];
        $result = $uploader->save($path);
        // echo $result['file']; 
      }catch (\Exception $e) {
        $this->messageManager->addError(__($e->getMessage()));
      }
    }
    $i++;
  }
}
?>
Related Topic