cancel
Showing results for 
Search instead for 
Did you mean: 

Trigger an API Call on uploading Images + Magento2

Trigger an API Call on uploading Images + Magento2

Hello Community,

I seek help and advice in a challenge which I am facing when I upload images in Magento2

 

When we upload images in Magento2 Admin backend - I need to trigger an API call to which I send the images in the bytecode / rawdata format and store the response which I receive from the API in an attribute.

 

I would be obliged if the experts on this forum can give me some directions and steps to execute this task.

 

Thanks for all the guidance and help.

1 REPLY 1

Re: Trigger an API Call on uploading Images + Magento2

When we upload images in Magento2 Admin backend For Products, there is event available in Magento named as : 

catalog_product_gallery_upload_image_after

You can use this observer to do some extra work, or call any API.
Example : 

1) Create file : <magento-root>/app/code/Vendor/ModuleName/etc/events.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="catalog_product_gallery_upload_image_after">
        <observer name="vendor_modulename_product_gallery_upload_image_after" instance="Vendor\ModuleName\Observer\CatalogProductImageSaveAfter" />
    </event>
</config>


2) Create File : <magento-root>app/code/Vendor/ModuleName/Observer/CatalogProductImageSaveAfter.php

<?php
namespace Vendor\ModuleName\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

class CatalogProductImageSaveAfter implements ObserverInterface
{
    /**
     * @var \Magento\Framework\DataObject\Copy
     */
    protected $objectCopyService;

    /**
     * @param \Magento\Framework\DataObject\Copy $objectCopyService
     * ...
     */
    public function __construct(
        \Magento\Framework\DataObject\Copy $objectCopyService
    ) {
        $this->objectCopyService = $objectCopyService;
    }

    /**
     * @param \Magento\Framework\Event\Observer $observer
     * @return $this|void
     */
    public function execute(Observer $observer)
    {
        try {
            $image = $observer->getEvent()->getData('result');
            // TODO : Your Logic Here
            return $this;
        } catch (\Exception $exception) {
            // TODO : Silence Or Log The Error
        }
    }
}

After that Run the Magento commands :

php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento setup:static-content:deploy -f
php bin/magento cache:flush


And then try to add the Image and in the console check the corresponding ajax request , you can see the results In the Console :

vardump($image);

See The Image 

Click on 'Kudos' & Accept as Solution to encourage to write more answers !