Magento – magento2 how to upload image into databse table from front end

file uploadimage-uploadmagento2

this is my input form given below what are the steps to save the image in database

<html>   
<body>
<form action="<?php echo $this->getUrl("helloworld/index/FileUpload");?>" method="post" enctype="multipart/form-data">

    <label for="bs_image">Image</label>
    <input type="file" id="bs_image" name="bs_image" required="true"/>
    <input type="submit" value="Submit" />

</form>
</body>
</html>

Best Answer

I believe you have service contracts, models, and resource models for your DB table in your Module.

public $cvFilePath;

    public function __construct(
        Context $context,
        CustomRepositoryInterface $customRepository,
        \Magento\Framework\Filesystem $filesystem,
        \Magento\MediaStorage\Model\File\UploaderFactory $fileUploaderFactory,
    )
    {
    parent::__construct($context);
        $this->customRepository = $customRepository;
        $this->_mediaDirectory       = $filesystem->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA);
        $this->_fileUploaderFactory  = $fileUploaderFactory;        
    }


    /**
     * upload applicant's CV
     *
     * @param string $redirectUrl
     *
     * @return string
     * */
    protected function _uploadCV($redirectUrl)
    {
        if(isset($_FILES['cv']['name']) && $_FILES['cv']['name'] != '')
        {
            try
            {
        // files would be saved in the path: magento_root/pub/media/bs_media
                $this->cvFilePath = $this->_mediaDirectory->getAbsolutePath('career/cv/');

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

                /** Allowed extension types */
                $uploader->setAllowedExtensions(['doc', 'pdf', 'docx']);

                $uploader->setAllowRenameFiles(TRUE);

                $cvFile = str_replace(' ', '_', $_FILES['cv']['name']);

                /** upload file in folder "career/cv/" */
                $result = $uploader->save($this->cvFilePath, $cvFile);

                if($result['file'])
                {
            // here you would save form data in DB table by repository interface
            // image file name is $result['file']                

                }
            }
            catch (\Exception $e)
            {
                $this->messageManager->addErrorMessage($e->getMessage());
                $this->_redirect($redirectUrl);
                return FALSE;
            }
        }
    }
Related Topic