Magento – Magento 2 : How to upload image from frontend

frontendimage-uploadmagento2

I want to add a feedback form in frontend, with an image upload field, How to save form data and images in database?

Best Answer

First, you should be add input type file at form and also add enctype='multipart/form-data' and

    <!-- -->
    <div class="field image">
        <label class="label" for="image"><span><?php /* @escapeNotVerified */ echo __('Image') ?></span></label>
        <div class="control">
            <input name="image" id="image" title="<?php /* @escapeNotVerified */ echo __('image') ?>"   type="file" />
        </div>
    </div>

At controller, you need upload image via

Magento\MediaStorage\Model\File\UploaderFactory

Add below class in __construct functions and execute function of controller:

 <?php
 namespace [Namespace];

use  Magento\Framework\App\Filesystem\DirectoryList;
class [MyClass]
{

 protected $uploaderFactory;
 protected $adapterFactory;
 protected $filesystem;

    public function  __construct(
            .....
            \Magento\MediaStorage\Model\File\UploaderFactory $uploaderFactory,
            \Magento\Framework\Image\AdapterFactory $adapterFactory,
            \Magento\Framework\Filesystem $filesystem
            .....
    )
    {
        .........
        $this->uploaderFactory = $uploaderFactory;
        $this->adapterFactory = $adapterFactory;
        $this->filesystem = $filesystem;
    }
     public function execute()
    {
        try{
            $uploaderFactory = $this->uploaderFactory->create(['fileId' => 'image']);
            $uploaderFactory->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
            $imageAdapter = $this->adapterFactory->create();
            /* start of validated image */
            $uploaderFactory->addValidateCallback('custom_image_upload',
                $imageAdapter,'validateUploadFile');
            $uploaderFactory->setAllowRenameFiles(true);
            $uploaderFactory->setFilesDispersion(true);
            $mediaDirectory = $this->filesystem->getDirectoryRead(DirectoryList::MEDIA);
            $destinationPath = $mediaDirectory->getAbsolutePath('custom_image');
            $result = $uploaderFactory->save($destinationPath);
            if (!$result) {
                throw new LocalizedException(
                    __('File cannot be saved to path: $1', $destinationPath)
                );
            }
            /* you need yo save image 
                 $result['file'] at datbaseQQ 
            */
            $imagepath = $result['file'];
            //
        } catch (\Exception $e) {
        }
    }
}

Note

$destinationPath give the path till magentoDir/pub/media/custom_image and $result content below

enter image description here

Related Topic