Back to Top

Upload Image by Uppy on Frontend in Magento 2.4.7

Updated 6 May 2024

In Magento 2.4.7 we can upload files using Uppy JS library. Here, We will learn how to upload an image on the frontend in Magento 2

First, we need to create the route file with the name routes.xml

Code for etc/frontend/routes.xml file

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route id="upload" frontName="upload">
            <module name="Webkul_ImageUploader" />
        </route>
    </router>
</config>

Then, we need to create the controller file, Controller/Index/Index.php

Code for Controller/Index/Index.php file

Searching for an experienced
Magento 2 Company ?
Find out More
<?php
namespace Webkul\ImageUploader\Controller\Index;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;

class Index extends Action
{
    private $pageFactory;

    public function __construct(
        Context $context,
        PageFactory $pageFactory
    ) {
        parent::__construct($context);
        $this->pageFactory = $pageFactory;
    }

    public function execute()
    {
        return $this->pageFactory->create();
    }
}

Now, we need to create a layout file with the name upload_index_index.xml.

Code for view/frontend/layout/upload_index_index.xml file.

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block class="Magento\Framework\View\Element\Template" name="imageupload_form" template="Webkul_ImageUploader::form.phtml" />
        </referenceContainer>
    </body>
</page>

In the templates folder, we need to create a template file with the name form.phtml to view the form.

Code for view/frontend/templates/form.phtml file

<button type="button" class="upload-img-btn">browse files</button>

<button class="delete" style="display: none;">X</button>
<div class="img-preview"></div>

<div id="uppy-root"></div>

<script type="text/x-magento-init">
{
    "#uppy-root": {
        "Webkul_ImageUploader/js/uppy-init": {
            "action": "<?= $block->getUrl('upload/index/uploadimage') ?>"
        }
    }
}
</script>
file-upload-button

In the js folder, we need to create a js file with the name uppy-init.phtml to initialize the uppy.

Code for view/frontend/web/js/uppy-init.js file

define([
    'jquery',
    'jquery/uppy-core'
    ], function($){
        $.widget('mage.intUppy', {
            /**
             * Widget initialization
             * @private
             */
             _create: function() {
                config = this.options;
                $('.upload-img-btn').on('click', function() {
                    $('.uppy-Dashboard-input:first').click();
                })
                $('.delete').on('click', function() {
                    $('.uppy-StatusBar-actionBtn').click();
                    $('.img-preview').html('');
                    $('.delete').css('display', 'none');
                })

                const uppy = new Uppy.Uppy({
                    autoProceed: true,
                    restrictions: {
                        maxFileSize: 2000000,
                        maxNumberOfFiles: 1,
                        minNumberOfFiles: 1,
                        allowedFileTypes: ['image/*']
                    },
                });
        
                uppy.use(Uppy.Dashboard, {
                    trigger: '#select-files',
                    inline: true,
                    target: '#uppy-root',
                });
        
                uppy.use(Uppy.XHRUpload, {
                    endpoint: config.action,
                    fieldName: 'image',
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                });
        
                uppy.on('complete', function (result) {
                    $('.delete').css('display', 'block');
                    console.log('Upload successful:', result.successful[0].response.body.fileName);
                    var imgpreview = $('.uppy-Dashboard-files').html();
                    $('.img-preview').html(imgpreview);
                });
            }
        });

    return $.mage.intUppy;
});

We need to create a controller file with the name UploadImage.php to upload the file.

Code for Controller/Index/UploadImage.php file

<?php
namespace Webkul\ImageUploader\Controller\Index;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\MediaStorage\Model\File\UploaderFactory as MediaUploaderFactory;
use Psr\Log\LoggerInterface;

class UploadImage extends Action
{
    private $resultJsonFactory;
    private $mediaUploaderFactory;
    private $logger;
    private $mediaDirectory;

    public function __construct(
        Context $context,
        JsonFactory $resultJsonFactory,
        MediaUploaderFactory $mediaUploaderFactory,
        DirectoryList $directoryList,
        LoggerInterface $logger
    ) {
        parent::__construct($context);
        $this->resultJsonFactory = $resultJsonFactory;
        $this->mediaUploaderFactory = $mediaUploaderFactory;
        $this->logger = $logger;
        $this->mediaDirectory = $directoryList->getPath(DirectoryList::MEDIA);
    }

    public function execute()
    {
        $result = $this->resultJsonFactory->create();
        try {
            $fileName = $this->upload('image');
            return $result->setData(['fileName' => $fileName]);
        } catch (\Exception $e) {
            return $result->setData(['error' => $e->getMessage()]);
        }
    }
    
    public function upload($fileId)
    {
        try {
            $uploader = $this->mediaUploaderFactory->create(['fileId' => $fileId]);
            $uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
            $uploader->setAllowRenameFiles(true);
            $uploader->setFilesDispersion(true);
            $result = $uploader->save($this->mediaDirectory . '/mymodule');
            return $result['file'];
        } catch (\Exception $e) {
            $this->logger->critical($e->getMessage());
            return false;
        }
    }
}
file-upload

Hire Magento Developers | Certified Adobe Commerce

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home