1

I created some file upload functionality through a custom module in Magento 2 category tab. I don't know how to save the file in database. How would I do that?

3 Answers 3

1
add use Magento\Framework\UrlInterface;
add use Magento\Framework\Filesystem;

...
$imageName = $this->uploadFileAndGetName('input_name', $this->fileSystem->getDirectoryWrite(DirectoryList::MEDIA)->getAbsolutePath($subdir_of_your_choice.'/image'));
$your_model->setImage($imageName);
Sign up to request clarification or add additional context in comments.

Comments

0

You don't save the file in DB, only the name :

    public function __construct(
    ....
    \Magento\Framework\File\UploaderFactory $uploaderFactory,
    ...
) {
    ......
    $this->uploaderFactory = $uploaderFactory;
    .....
}

public function uploadFileAndGetName($input, $destinationFolder)
{
    try {

            $uploader = $this->uploaderFactory->create(array('fileId' => $input));
            /** test The File with Callback here */
            $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());
        }
    }
    return '';
}

1 Comment

hi friend thanks for your answer.but am little bit confused, am here adding field in category tab through InstallData.php so can u tell me how to make the file name saved in table
0

The following code is to upload file in custom table,

namespace MODULE\NAMESPACE\Controller\Index;
use Magento\Framework\App\Filesystem\DirectoryList;
class NAMESPACE extends \Magento\Framework\App\Action\Action
{
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Customer\Model\Session $customerSession,
        \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
        \Magento\Framework\Message\ManagerInterface $messageManager
        ) {
        $this->_customerSession = $customerSession;
        $this->resultJsonFactory = $resultJsonFactory;
        $this->messageManager = $messageManager;
        parent::__construct($context);
    }
    public function execute()
    {
        $params =  $this->getRequest()->getParams();
        $result = $this->resultJsonFactory->create();
        $resultRedirect = $this->resultRedirectFactory->create();
        if ($params) {
            $data['name'] = $params['name'];
            $data['email_id'] = $params['email'];
            $data['city'] = isset($params['city'])? $params['city'] : '';
            $data['store_id'] = $params['storeid'];

            $model = $this->_objectManager->create('MODEL FILE PATH of specific table');
            try{
                $uploader = $this->_objectManager->create(
                    'Magento\MediaStorage\Model\File\Uploader',
                    ['fileId' => 'FIELDNAME']
                );
                $uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
                /** @var \Magento\Framework\Image\Adapter\AdapterInterface $imageAdapter */
                $imageAdapter = $this->_objectManager->get('Magento\Framework\Image\AdapterFactory')->create();
                $uploader->setAllowRenameFiles(true);
                $uploader->setFilesDispersion(true);
                /** @var \Magento\Framework\Filesystem\Directory\Read $mediaDirectory */
                $mediaDirectory = $this->_objectManager->get('Magento\Framework\Filesystem')
                    ->getDirectoryRead(DirectoryList::MEDIA);
                $result = $uploader->save($mediaDirectory->getAbsolutePath('FOLDERNAME'));
                    if($result['error']==0)
                    {
                        $data['offline_bill'] = 'FOLDERNAME' . $result['file'];
                    }
            } catch (\Exception $e) {

            }
            $model->setData($data);            
            try
            {
                $model->save();
                $this->messageManager->addSuccess(__('The form submitted successfully.'));
            }
            catch (\Magento\Framework\Exception\LocalizedException $e) 
            {
                $this->messageManager->addError($e->getMessage());
            }
            return $resultRedirect->setPath(REDIRECT PATH);
        }
    }
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.