Magento – check file uploaded or not without $_FILES in Magento 2

coding-standardsfatal errorfile uploadmagento-2.1magento2

I'm checking condition like file uploaded or not, for that I used $_FILES but as magento 2 coding standards we cannot use $_FILES.

if ($id) {
    $model->load($id);
}

//if (isset($_FILES['file']) && $_FILES['file']['name'] != '') {
    $imageFile = $this->helper->uploadFile('file');
    $model->setFile($imageFile);
//}

So I created helper class to upload file

public function uploadFile($scope)
{   
   try {
        $uploader = $this->_fileUploaderFactory->create(['fileId' => $scope]);
        $uploader->setAllowRenameFiles(true);
        $uploader->setFilesDispersion(true);
        $uploader->setAllowCreateFolders(true);

        if ($uploader->save($this->getBaseDir())) {
            return $uploader->getUploadedFileName();    
        }

    } catch (\Exception $e) { 
        throw new $e('File was not uploaded');
    }
}

But when I have no upload any file it's show fatal error "File was not uploaded".
How we check that file was selected in field or not?

Best Answer

This will resolve the problem. Put this in controller.

$files = $this->getRequest()->getFiles()

Here is Magento2 :: Accessing $_FILES using Magento Framework