0

I'm trying to upload image in my custom module but I always getting the "The file was not uploaded." error. I trace the code and all I can say is the $this->uploader->create() is not working.

Here my sample code.

<?php

/**
 * Grid Admin Cagegory Map Record Save Controller.
 * @category  Webkul
 * @package   Testing_Basic
 * @author    Webkul
 * @copyright Copyright (c) 2010-2016 Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html
 */
namespace Testing\Basic\Controller\Adminhtml\Contact;

use Magento\Framework\App\Action\Context;
use Testing\Basic\Model\ContactFactory;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\MediaStorage\Model\File\UploaderFactory;
use Magento\Framework\Image\AdapterFactory;
use Magento\Framework\Filesystem;

class Save extends \Magento\Backend\App\Action
{
    /**
     * @var \Testing\Basic\Model\ContactFactory
     */
    var $contactFactory;

    protected $uploaderFactory;
    protected $adapterFactory;
    protected $fileSystem;
    protected $allowedExtensions = ['jpg', 'jpeg', 'png'];
    protected $fileId = 'your_file_id';
    protected $oldImage = null;

    /**
     * @param \Magento\Backend\App\Action\Context $context
     * @param \Testing\Basic\Model\ContactFactory $contactFactory
     */
    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Framework\Filesystem\DirectoryList $dir,
        UploaderFactory $uploaderFactory,
        Filesystem $fileSystem,
        \Testing\Basic\Model\ContactFactory $contactFactory,
        AdapterFactory $adapterFactory
    ) {
        parent::__construct($context);
        $this->_dir = $dir;
        $this->uploaderFactory = $uploaderFactory;
        $this->contactFactory = $contactFactory;
        $this->fileSystem = $fileSystem;
        $this->adapterFactory = $adapterFactory;
    }

    /**
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     * @SuppressWarnings(PHPMD.NPathComplexity)
     */
    public function execute()
    {
        $data = $this->getRequest()->getPostValue();
        $img = $this->getRequest()->getFiles();
        /* var_dump($img);die; */
        if (!$data) {
            $this->_redirect('contact/contact/addrow');
            return;
        }
        if(isset($_FILES['img_title']['name']) && (file_exists($_FILES['img_title']['tmp_name'])))
        {
            $destinationPath = $this->getDestinationPath();
            try{
                $imageAdapter = $this->adapterFactory->create();
                $uploaderFactory = $this->uploaderFactory->create(['fileId' => 'image'])
                    ->setAllowCreateFolders(true)
                    ->setAllowRenameFiles(true)
                    ->setAllowedExtensions($this->allowedExtensions)
                    ->addValidateCallback('custom_image_upload',$imageAdapter,'validateUploadFile');
                var_dump('asdad');die;
                $mediaDirectory = $this->filesystem->getDirectoryRead(DirectoryList::MEDIA);
                $destinationPath = $mediaDirectory->getAbsolutePath('');
                $result = $uploaderFactory->save($destinationPath);
                if (!$result) {
                    throw new LocalizedException(
                        __('File cannot be saved to path: $1', $destinationPath)
                    );
                }
                $imagePath = $result['file'];
                var_dump($imagePath);die;
                $data['img_title'] = $imagePath;
            } catch (\Exception $e) {
                var_dump($e->getMessage());die;
            }
        }
        try {
            $rowData = $this->contactFactory->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('contact/contact/index');
    }

    /**
     * @return bool
     */
    protected function _isAllowed()
    {
        return $this->_authorization->isAllowed('Testing_Basic::save');
    }

    public function getDestinationPath()
    {
        return $this->fileSystem
            ->getDirectoryWrite(DirectoryList::MEDIA)
            ->getAbsolutePath('/');
    }
}
1

1 Answer 1

0

I think you use wrong AdapterFactory.Try this code

<?php
namespace YourNamespace\YourModule\Controller;

use Magento\Framework\App\Action\Context;
use Magento\Framework\Message\ManagerInterface;
use Magento\Framework\Filesystem;
use Magento\MediaStorage\Model\File\UploaderFactory;

class YourController extends \Magento\Framework\App\Action\Action
{
    /**
     * @var \Magento\Framework\Message\ManagerInterface
     */
    protected $messageManager;

    /**
     * @var \Magento\Framework\Filesystem $filesystem
     */
    protected $filesystem;

    /**
     * @var \Magento\MediaStorage\Model\File\UploaderFactory $fileUploader
     */
    protected $fileUploader;

    public function __construct(
        Context $context,
        ManagerInterface $messageManager,
        ...
        Filesystem $filesystem,
        UploaderFactory $fileUploader
    )
    {
        $this->messageManager       = $messageManager;
        ...
        $this->filesystem           = $filesystem;
        $this->fileUploader         = $fileUploader;

        $this->mediaDirectory = $filesystem->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA);

        parent::__construct($context);
    }

    public function execute()
    {
        // your code

        $uploadedFile = $this->uploadFile();

        // your code
    }

    public function uploadFile()
    {
        // this folder will be created inside "pub/media" folder
        $yourFolderName = 'your-custom-folder/';

        // "my_custom_file" is the HTML input file name
        $yourInputFileName = 'my_custom_file';

        try{
            $file = $this->getRequest()->getFiles($yourInputFileName);
            $fileName = ($file && array_key_exists('name', $file)) ? $file['name'] : null;

            if ($file && $fileName) {
                $target = $this->mediaDirectory->getAbsolutePath($yourFolderName);        

                /** @var $uploader \Magento\MediaStorage\Model\File\Uploader */
                $uploader = $this->fileUploader->create(['fileId' => $yourInputFileName]);

                // set allowed file extensions
                $uploader->setAllowedExtensions(['jpg', 'pdf', 'doc', 'png', 'zip']);

                // allow folder creation
                $uploader->setAllowCreateFolders(true);

                // rename file name if already exists 
                $uploader->setAllowRenameFiles(true);

                // rename the file name into lowercase
                // but this one is not working
                // we can simply use strtolower() function to rename filename to lowercase
                // $uploader->setFilenamesCaseSensitivity(true);

                // enabling file dispersion will 
                // rename the file name into lowercase
                // and create nested folders inside the upload directory based on the file name
                // for example, if uploaded file name is IMG_123.jpg then file will be uploaded in
                // pub/media/your-upload-directory/i/m/img_123.jpg
                // $uploader->setFilesDispersion(true);         

                // upload file in the specified folder
                $result = $uploader->save($target);

                //echo '<pre>'; print_r($result); exit;

                if ($result['file']) {
                    $this->messageManager->addSuccess(__('File has been successfully uploaded.')); 
                }

                return $target . $uploader->getUploadedFileName();
            }
        } catch (\Exception $e) {
            $this->messageManager->addError($e->getMessage());
        }

        return false;
    }
}
2
  • What do you mean by that? I check and compare your code and mine and we are using the same path and same adapter factory.
    – Daniel_C
    Mar 31, 2020 at 14:43
  • I haven't use this $imageAdapter = $this->adapterFactory->create();
    – Jinesh
    Mar 31, 2020 at 15:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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