1

I'm using Magento 2 CE Version 2.1.0. I would like to validate that uploaded image should not exceed 5MB.

app\code\Custom\Module\Controller\Posts\Post.php

public function execute() {
    $uploader = $this->_fileUploaderFactory->create(['fileId' => 'picture1']);
    $uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
    $uploader->addValidateCallback('picture1', $uploader, 'validateUploadFile');
}

public function validateUploadFile($filePath) {
    echo "here";
    exit;
}

It's not calling validateUploadFile function within that file.

1

It is because the second parameter of addValidateCallback is the callback object.

In your case you specified the $uploader object but the validateUploadFile is defined in the current class.

So you need to call the following instead:

$uploader->addValidateCallback('picture1', $this, 'validateUploadFile');
| improve this answer | |
  • Strange. Still not working :( – Jackson Aug 31 '16 at 9:37
  • @MikeSmith try to change the content of your validateUploadFile method with an exception thrown like throw new \Magento\Framework\Exception\LocalizedException(__('Error')); – Raphael at Digital Pianism Aug 31 '16 at 9:39
  • I have done {public function validateUploadFile($filePath) { try { } catch (\Magento\Framework\Exception\LocalizedException $e) { echo $e->getMessage();exit; $this->messageManager->addError($e->getMessage()); }} Still it's not going in to that function. I have also tried by changing name of function } – Jackson Aug 31 '16 at 9:44
  • @MikeSmith try to do this instead: public function validateUploadFile($filePath) { throw new \Magento\Framework\Exception\LocalizedException(__('Error'))‌​; } just to see if you're function is getting called – Raphael at Digital Pianism Aug 31 '16 at 9:45
  • I tried public function validateUploadFile($filePath) { throw new \Exception('Errors'); } But still it's not calling this function – Jackson Aug 31 '16 at 9:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.