I am new to magento 2. I have been overriding a module in which I am trying to post images through a form. Here is my template file code:
<form action="somecontroller.." enctype="multipart/form-data">
<!-- here is the module code -->
<div class="field review-field-media">
<label class="label"><span><?php echo __('Attachments') ?></span></label>
<div class="control">
<input type="file" name="review_media" id="review_media" accept="image/*" multiple="multiple" />
</div>
</div>
</form>
and here is my controller execute method:
public function execute() {
$returnable = parent::execute();
$bgImage = $this->getRequest()->getFiles('review_media');
$fileName = ($bgImage && array_key_exists('name', $bgImage)) ? $bgImage['name'] : null;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
if ($bgImage && $fileName) {
try {
$uploader = $objectManager->create(
'Magento\MediaStorage\Model\File\Uploader', ['fileId' => 'review_media']
);
$uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
$imageAdapterFactory = $objectManager->get('Magento\Framework\Image\AdapterFactory')
->create();
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(true);
$uploader->setAllowCreateFolders(true);
$mediaDirectory = $objectManager->get('Magento\Framework\Filesystem')
->getDirectoryRead(DirectoryList::MEDIA);
$result = $uploader->save($mediaDirectory->getAbsolutePath('review_images'));
$model->setBgImage($result['file']);
} catch (\Exception $e) {
if ($e->getCode() == 0) {
$this->messageManager->addError($e->getMessage());
}
}
}
return $returnable;
}
Now the problem is that when I upload multiple images through frontend and debug the code I get null in $bgImage = $this->getRequest()->getFiles('review_media');
But when I upload a single file $bgImage
shows the requested file to upload. Even in case of single image file when $uploader =$objectManager>create('Magento\MediaStorage\Model\File\Uploader', ['fileId' => 'review_media']);
I get exception that image was not uploaded and the later code is not executed.
IMPORTANT : I am following magento's zend code so don't want to go with php $_FILES[] method
Million thanks in advance!