I am getting the file was not uploaded error in Magento 2 when I edit the form in the Magento 2 backend.
When I try to save the form it shows an error. The problem is that it requires me to choose the image again even though it is already there. Kindly help me to resolve this problem.
My save.php file.
<?php
namespace Webkul\Grid\Controller\Adminhtml\Grid;
use Magento\Framework\App\Filesystem\DirectoryList;
class Save extends \Magento\Backend\App\Action
{
/**
* @var \AdminGrid\Grid\Model\GridFactory
*/
var $gridFactory;
protected $_mediaDirectory;
protected $_fileUploaderFactory;
/**
* @param \Magento\Backend\App\Action\Context $context
* @param \AdminGrid\Grid\Model\GridFactory $gridFactory
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Webkul\Grid\Model\GridFactory $gridFactory,
\Magento\Framework\Filesystem $filesystem,
\Magento\MediaStorage\Model\File\UploaderFactory $fileUploaderFactory
) {
parent::__construct($context);
$this->gridFactory = $gridFactory;
$this->_mediaDirectory = $filesystem->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA);
$this->_fileUploaderFactory = $fileUploaderFactory;
}
/**
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function execute()
{
$resultRedirect = $this->resultRedirectFactory->create();
try{
$target = $this->_mediaDirectory->getAbsolutePath('mycustomfolder/');
$targetOne = "mycustomfolder/";
/** @var $uploader \Magento\MediaStorage\Model\File\Uploader */
$uploader = $this->_fileUploaderFactory->create(['fileId' => 'image']);
/** Allowed extension types */
$uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png', 'zip', 'doc']);
/** rename file name if already exists */
$uploader->setAllowRenameFiles(true);
/** upload file in folder "mycustomfolder" */
$result = $uploader->save($target);
}
catch (Exception $e)
{
$this->messageManager->addError($e->getMessage());
}
$data = $this->getRequest()->getPostValue();
$data['image'] = $targetOne.$result['file'];
if (!$data) {
$this->_redirect('grid/grid/addrow');
return;
}
try {
$rowData = $this->gridFactory->create();
$rowData->setData($data);
if (isset($data['id'])) {
$rowData->setEntityId($data['id']);
}
$rowData->save();
$this->messageManager->addSuccess(__('Row data has been successfully saved.'));
} catch (\Exception $e) {
$this->messageManager->addError(__($e->getMessage()));
}
$this->_redirect('grid/grid/index');
}
/**
* @return bool
*/
protected function _isAllowed()
{
return $this->_authorization->isAllowed('Webkul_Grid::save');
}
}