I have prepared one module in which I have used Image upload button. And My button is working fine unless I am not entering any "Disallowed file type". When I enter any disallowed file type it gives me exception.
I have written the below function to upload file of my required file-type and to handle exception. I have also prepared required block and model file for image upload. I have followed this post
public function uploadFileAndGetName($input, $destinationFolder, $data)
{
try {
if (isset($data[$input]['delete'])) {
return '';
} else {
$uploader = $this->uploaderFactory->create(['fileId' => $input]);
$uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(true);
$uploader->setAllowCreateFolders(true);
$result = $uploader->save($destinationFolder);
return $result['file'];
}
} catch (\Exception $e) {
if ($e->getCode() != \Magento\Framework\File\Uploader::TMP_NAME_EMPTY) {
throw new FrameworkException($e->getMessage());
} else {
if (isset($data[$input]['value'])) {
return $data[$input]['value'];
}
}
}
return '';
}
When I enter any disallowed file-type, it gives me blank page and gives error "Disallowed file type".
If anyone faced this issue, please help me.
Best Answer
In my case it was due to the Exception class in the throw block. I'm using magento 2.17, the Uploader class throws Exception class. Please check framework/file/Uploader.php:: _validateFile(). Makesure the Exception class in the Uploader throw block and your Exception reference in your code is identical. My case it is worked: framework/file/Uploader.php:
And in my code it was like: