I am working on admin form in which i am trying to upload the file but it is giving me the $_File array is empty which means i am not getting file. Following is my code in form.
$fieldset->addField(
'file',
'file',
array(
'name' => 'file',
'label' => __('File'),
'title' => __('File')
)
);
Here is code of my controller
public function __construct(
Context $context,
\Magento\Framework\Filesystem $filesystem,
\Magento\MediaStorage\Model\File\UploaderFactory $fileUploaderFactory
) {
$this->_mediaDirectory = $filesystem->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA);
$this->_fileUploaderFactory = $fileUploaderFactory;
parent::__construct($context);
}
public function execute()
{
/** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultRedirectFactory->create();
try{
$target = $this->_mediaDirectory->getAbsolutePath('mycustomfolder/');
/** @var $uploader \Magento\MediaStorage\Model\File\Uploader */
$uploader = $this->_fileUploaderFactory->create(['fileId' => 'file']);
/** 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);
if ($result['file']) {
$this->messageManager->addSuccess(__('File has been successfully uploaded'));
}
} catch (\Exception $e) {
$this->messageManager->addError($e->getMessage());
}
return $this->resultRedirectFactory->create()->setPath(
'*/*/upload', ['_secure'=>$this->getRequest()->isSecure()]
);
}