0

In Magento 2.3.0 How to Upload the image into the custom admin ui component form ?

I have tried many codes but "The file was not uploaded" error occured into the uploading

My Code:

adminhtml/ui_component/custom_form.xml

            <field name="swatch_image">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="dataType" xsi:type="string">string</item>
                <item name="label" xsi:type="string" translate="true">Swatch Image</item>
                <item name="visible" xsi:type="boolean">true</item>
                <item name="formElement" xsi:type="string">fileUploader</item>
                <item name="elementTmpl" xsi:type="string">ui/form/element/uploader/uploader</item>
                <item name="previewTmpl" xsi:type="string">Cirklestudio_Customproduct/image-preview</item>
                <item name="required" xsi:type="boolean">false</item>
                <item name="uploaderConfig" xsi:type="array">
                    <item name="url" xsi:type="url" path="customproduct/customoption/upload"/>
                </item>
            </item>
        </argument>
        </field>

adminhtml/web/template/image-preview.html

<div class="file-uploader-summary">
<div class="file-uploader-preview">
    <a attr="href: $parent.getFilePreview($file)" target="_blank">
        <img
            class="preview-image"
            tabindex="0"
            event="load: $parent.onPreviewLoad.bind($parent)"
            attr="
                src: $parent.getFilePreview($file),
                alt: $file.name">
    </a>

    <div class="actions">
        <button
            type="button"
            class="action-remove"
            data-role="delete-button"
            attr="title: $t('Delete image')"
            click="$parent.removeFile.bind($parent, $file)">
            <span translate="'Delete image'"/>
        </button>
    </div>
</div>

<div class="file-uploader-filename" text="$file.name"/>
<div class="file-uploader-meta">
    <text args="$file.previewWidth"/>x<text args="$file.previewHeight"/>
</div>

This is my Upload Controller

Cirklestudio\Customproduct\Controller\Adminhtml\Customoption\Upload.php

<?php
namespace Cirklestudio\Customproduct\Controller\Adminhtml\Customoption;

use Magento\Framework\Controller\ResultFactory;

/** * Class Upload */ 
class Upload extends \Magento\Backend\App\Action { 
/** 
* Image uploader * 
* @var \Magento\Catalog\Model\ImageUploader */ protected $imageUploader;

/**
* Upload constructor.
*
* @param \Magento\Backend\App\Action\Context $context
* @param \Magento\Catalog\Model\ImageUploader $imageUploader
*/
public function __construct(
    \Magento\Backend\App\Action\Context $context,
    \Cirklestudio\Customproduct\Model\ImageUploader $imageUploader
) {
    parent::__construct($context);
    $this->imageUploader = $imageUploader;
}

/**
 * Check admin permissions for this controller
 *
 * @return boolean
 */
protected function _isAllowed()
{
    return $this->_authorization->isAllowed('Cirklestudio_Customproduct::customoption');
}

/**
 * Upload file controller action
 *
 * @return \Magento\Framework\Controller\ResultInterface
 */
public function execute()
{
    try {
        $result = $this->imageUploader->saveFileToTmpDir('logo');

        $result['cookie'] = [
            'name' => $this->_getSession()->getName(),
            'value' => $this->_getSession()->getSessionId(),
            'lifetime' => $this->_getSession()->getCookieLifetime(),
            'path' => $this->_getSession()->getCookiePath(),
            'domain' => $this->_getSession()->getCookieDomain(),
        ];
    } catch (\Exception $e) {
        $result = ['error' => $e->getMessage(), 'errorcode' => $e->getCode()];
    }
    return $this->resultFactory->create(ResultFactory::TYPE_JSON)->setData($result);
}

}

Model (image uploader)

Cirklestudio\Customproduct\Model\ImageUploader.php

<?php

/** 
* Simple Hello World Module 
** @category QaisarSatti 
* @package QaisarSatti_HelloWorld 
* @author Muhammad Qaisar Satti 
* @Email qaisarssatti@gmail.com * */
namespace Cirklestudio\Customproduct\Model;

/** 
* Catalog image uploader */ 
class ImageUploader { 
    /** 
    * Core file storage database 
    * 
    * @var \Magento\MediaStorage\Helper\File\Storage\Database */ 
    protected $coreFileStorageDatabase;

/**
 * Media directory object (writable).
 *
 * @var \Magento\Framework\Filesystem\Directory\WriteInterface
 */
protected $mediaDirectory;

/**
 * Uploader factory
 *
 * @var \Magento\MediaStorage\Model\File\UploaderFactory
 */
private $uploaderFactory;

/**
 * Store manager
 *
 * @var \Magento\Store\Model\StoreManagerInterface
 */
protected $storeManager;

/**
 * @var \Psr\Log\LoggerInterface
 */
protected $logger;

/**
 * Base tmp path
 *
 * @var string
 */
protected $baseTmpPath;

/**
 * Base path
 *
 * @var string
 */
protected $basePath;

/**
 * Allowed extensions
 *
 * @var string
 */
protected $allowedExtensions;

/**
 * ImageUploader constructor
 *
 * @param \Magento\MediaStorage\Helper\File\Storage\Database $coreFileStorageDatabase
 * @param \Magento\Framework\Filesystem $filesystem
 * @param \Magento\MediaStorage\Model\File\UploaderFactory $uploaderFactory
 * @param \Magento\Store\Model\StoreManagerInterface $storeManager
 * @param \Psr\Log\LoggerInterface $logger
 * @param string $baseTmpPath
 * @param string $basePath
 * @param string[] $allowedExtensions
 */
public function __construct(
    \Magento\MediaStorage\Helper\File\Storage\Database $coreFileStorageDatabase,
    \Magento\Framework\Filesystem $filesystem,
    \Magento\MediaStorage\Model\File\UploaderFactory $uploaderFactory,
    \Magento\Store\Model\StoreManagerInterface $storeManager,
    \Psr\Log\LoggerInterface $logger,
    $baseTmpPath,
    $basePath,
    $allowedExtensions
) {
    $this->coreFileStorageDatabase = $coreFileStorageDatabase;
    $this->mediaDirectory = $filesystem->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA);
    $this->uploaderFactory = $uploaderFactory;
    $this->storeManager = $storeManager;
    $this->logger = $logger;
    $this->baseTmpPath = $baseTmpPath;
    $this->basePath = $basePath;
    $this->allowedExtensions = $allowedExtensions;
}

/**
 * Set base tmp path
 *
 * @param string $baseTmpPath
 *
 * @return void
 */
public function setBaseTmpPath($baseTmpPath)
{
    $this->baseTmpPath = $baseTmpPath;
}

/**
 * Set base path
 *
 * @param string $basePath
 *
 * @return void
 */
public function setBasePath($basePath)
{
    $this->basePath = $basePath;
}

/**
 * Set allowed extensions
 *
 * @param string[] $allowedExtensions
 *
 * @return void
 */
public function setAllowedExtensions($allowedExtensions)
{
    $this->allowedExtensions = $allowedExtensions;
}

/**
 * Retrieve base tmp path
 *
 * @return string
 */
public function getBaseTmpPath()
{
    return $this->baseTmpPath;
}

/**
 * Retrieve base path
 *
 * @return string
 */
public function getBasePath()
{
    return $this->basePath;
}

/**
 * Retrieve base path
 *
 * @return string[]
 */
public function getAllowedExtensions()
{
    return $this->allowedExtensions;
}

/**
 * Retrieve path
 *
 * @param string $path
 * @param string $imageName
 *
 * @return string
 */
public function getFilePath($path, $imageName)
{
    return rtrim($path, '/') . '/' . ltrim($imageName, '/');
}

/**
 * Checking file for moving and move it
 *
 * @param string $imageName
 *
 * @return string
 *
 * @throws \Magento\Framework\Exception\LocalizedException
 */
public function moveFileFromTmp($imageName)
{
    $baseTmpPath = $this->getBaseTmpPath();
    $basePath = $this->getBasePath();

    $baseImagePath = $this->getFilePath($basePath, $imageName);
    $baseTmpImagePath = $this->getFilePath($baseTmpPath, $imageName);

    try {
        $this->coreFileStorageDatabase->copyFile(
            $baseTmpImagePath,
            $baseImagePath
        );
        $this->mediaDirectory->renameFile(
            $baseTmpImagePath,
            $baseImagePath
        );
    } catch (\Exception $e) {
        throw new \Magento\Framework\Exception\LocalizedException(
            __('Something went wrong while saving the file(s).')
        );
    }

    return $imageName;
}

/**
 * Checking file for save and save it to tmp dir
 *
 * @param string $fileId
 *
 * @return string[]
 *
 * @throws \Magento\Framework\Exception\LocalizedException
 */
public function saveFileToTmpDir($fileId)
{
    $baseTmpPath = $this->getBaseTmpPath();

    $uploader = $this->uploaderFactory->create(['fileId' => $fileId]);
    $uploader->setAllowedExtensions($this->getAllowedExtensions());
    $uploader->setAllowRenameFiles(true);

    $result = $uploader->save($this->mediaDirectory->getAbsolutePath($baseTmpPath));

    if (!$result) {
        throw new \Magento\Framework\Exception\LocalizedException(
            __('File can not be saved to the destination folder.')
        );
    }

    /**
     * Workaround for prototype 1.7 methods "isJSON", "evalJSON" on Windows OS
     */

    $result['tmp_name'] = str_replace('\\', '/', $result['tmp_name']);
    $result['path'] = str_replace('\\', '/', $result['path']);
    $result['url'] = $this->storeManager
            ->getStore()
            ->getBaseUrl(
                \Magento\Framework\UrlInterface::URL_TYPE_MEDIA
            ) . $this->getFilePath($baseTmpPath, $result['file']);
    $result['name'] = $result['file'];

    if (isset($result['file'])) {
        try {
            $relativePath = rtrim($baseTmpPath, '/') . '/' . ltrim($result['file'], '/');
            $this->coreFileStorageDatabase->saveFile($relativePath);
        } catch (\Exception $e) {
            $this->logger->critical($e);
            throw new \Magento\Framework\Exception\LocalizedException(
                __('Something went wrong while saving the file(s).')
            );
        }
    }

    return $result;
}

}

di.xml

<virtualType name="Cirklestudio\Customproduct\CustomproductImageUpload" type="Cirklestudio\Customproduct\Model\ImageUploader">
    <arguments>
            <argument name="baseTmpPath" xsi:type="string">test/tmp</argument>
            <argument name="basePath" xsi:type="string">test</argument>
            <argument name="allowedExtensions" xsi:type="array">
                <item name="jpg" xsi:type="string">jpg</item>
                <item name="jpeg" xsi:type="string">jpeg</item>
                <item name="gif" xsi:type="string">gif</item>
                <item name="png" xsi:type="string">png</item>
            </argument>
    </arguments>
</virtualType>
<type name="Cirklestudio\Customproduct\Controller\Adminhtml\Customoption\Upload">
    <arguments>
            <argument name="imageUploader" xsi:type="object">Cirklestudio\Customproduct\CustomproductImageUpload</argument>
    </arguments>
</type>
  • show your code that you have tried. – Manashvi Birla Mar 27 '19 at 7:39
  • Please check code – Hardik Makwana Mar 27 '19 at 7:59
  • try using this instead of fileUploader <item name="formElement" xsi:type="string">imageUploader</item> – Ghulam.M Mar 27 '19 at 14:11
  • I tried but not working same error occured "The file was not uploaded" – Hardik Makwana Mar 28 '19 at 5:07
  • How to modify the extended sales order grid in Magento 2 anyone? – Yo Yo Roshan Mar 18 at 6:20
0

Now issue is solve try this changes

adminhtml/ui_component/custom_form.xml

<field name="swatch_image">
    <argument name="data" xsi:type="array">
        <item name="config" xsi:type="array">
            <item name="dataType" xsi:type="string">string</item>
            <item name="label" xsi:type="string" translate="true">Upload Image</item>
            <item name="visible" xsi:type="boolean">true</item>
            <item name="formElement" xsi:type="string">fileUploader</item>
            <item name="elementTmpl" xsi:type="string">ui/form/element/uploader/uploader</item>
            <item name="previewTmpl" xsi:type="string">Cirklestudio_Customproduct/image-preview</item>
             <item name="uploaderConfig" xsi:type="array">
                <item name="url" xsi:type="url" path="customproduct/customoption/upload" >
                    <param name="target_element_id">swatch_image</param>
                    <param name="type">image</param>
                </item>
            </item>
        </item>
    </argument>
</field>

adminhtml/web/template/image-preview.html

<div class="file-uploader-summary">
    <div class="file-uploader-preview">
        <a attr="href: $parent.getFilePreview($file)" target="_blank">
            <img
                class="preview-image"
                tabindex="0"
                event="load: $parent.onPreviewLoad.bind($parent)"
                attr="
                    src: $parent.getFilePreview($file),
                    alt: $file.name">
        </a>

        <div class="actions">
            <button
                type="button"
                class="action-remove"
                data-role="delete-button"
                attr="title: $t('Delete image')"
                click="$parent.removeFile.bind($parent, $file)">
                <span translate="'Delete image'"/>
            </button>
        </div>
    </div>

    <div class="file-uploader-filename" text="$file.name"/>
    <div class="file-uploader-meta">
        <text args="$file.previewWidth"/>x<text args="$file.previewHeight"/>
    </div>
</div>

This is your Upload Controller

Cirklestudio\Customproduct\Controller\Adminhtml\Customoption\Upload.php

<?php

namespace Cirklestudio\Customproduct\Controller\Adminhtml\Customoption;

use Magento\Framework\Controller\ResultFactory;

class Upload extends \Magento\Backend\App\Action
{
    public $imageUploader;

    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Cirklestudio\Customproduct\Model\ImageUploader $imageUploader
    ) {
        parent::__construct($context);
        $this->imageUploader = $imageUploader;
    }
    public function execute()
    {
        try {
            $result = $this->imageUploader->saveFileToTmpDir('swatch_image');
            $result['cookie'] = [
                'name' => $this->_getSession()->getName(),
                'value' => $this->_getSession()->getSessionId(),
                'lifetime' => $this->_getSession()->getCookieLifetime(),
                'path' => $this->_getSession()->getCookiePath(),
                'domain' => $this->_getSession()->getCookieDomain(),
            ];
        } catch (\Exception $e) {
            $result = ['error' => $e->getMessage(), 'errorcode' => $e->getCode()];
        }
        return $this->resultFactory->create(ResultFactory::TYPE_JSON)->setData($result);
    }
}

Model (image uploader)

Cirklestudio\Customproduct\Model\ImageUploader.php

<?php

namespace Cirklestudio\Customproduct\Model;

class ImageUploader
{
    private $coreFileStorageDatabase;
    private $mediaDirectory;
    private $uploaderFactory;
    private $storeManager;
    private $logger;
    public $baseTmpPath;
    public $basePath;
    public $allowedExtensions;

    public function __construct(
        \Magento\MediaStorage\Helper\File\Storage\Database $coreFileStorageDatabase,
        \Magento\Framework\Filesystem $filesystem,
        \Magento\MediaStorage\Model\File\UploaderFactory $uploaderFactory,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Psr\Log\LoggerInterface $logger
    ) {
        $this->coreFileStorageDatabase = $coreFileStorageDatabase;
        $this->mediaDirectory = $filesystem->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA);
        $this->uploaderFactory = $uploaderFactory;
        $this->storeManager = $storeManager;
        $this->logger = $logger;
        $this->baseTmpPath = "Test/temp";
        $this->basePath = "Test";
        $this->allowedExtensions = ['jpg', 'jpeg', 'png'];
    }
    public function setBaseTmpPath($baseTmpPath)
    {
        $this->baseTmpPath = $baseTmpPath;
    }
    public function setBasePath($basePath)
    {
        $this->basePath = $basePath;
    }
    public function setAllowedExtensions($allowedExtensions)
    {
        $this->allowedExtensions = $allowedExtensions;
    }
    public function getBaseTmpPath()
    {
        return $this->baseTmpPath;
    }
    public function getBasePath()
    {
        return $this->basePath;
    }
    public function getAllowedExtensions()
    {
        return $this->allowedExtensions;
    }
    public function getFilePath($path, $imageName)
    {
        return rtrim($path, '/') . '/' . ltrim($imageName, '/');
    }
    public function moveFileFromTmp($imageName)
    {
        $baseTmpPath = $this->getBaseTmpPath();
        $basePath = $this->getBasePath();

        $baseImagePath = $this->getFilePath($basePath, $imageName);
        $baseTmpImagePath = $this->getFilePath($baseTmpPath, $imageName);

        try {
            $this->coreFileStorageDatabase->copyFile(
                $baseTmpImagePath,
                $baseImagePath
            );
            $this->mediaDirectory->renameFile(
                $baseTmpImagePath,
                $baseImagePath
            );
        } catch (\Exception $e) {
            throw new \Magento\Framework\Exception\LocalizedException(
                __('Something went wrong while saving the file(s).')
            );
        }

        return $imageName;
    }
    public function saveFileToTmpDir($fileId)
    {
        $baseTmpPath = $this->getBaseTmpPath();
        $uploader = $this->uploaderFactory->create(['fileId' => $fileId]);
        $uploader->setAllowedExtensions($this->getAllowedExtensions());
        $uploader->setAllowRenameFiles(true);
        $result = $uploader->save($this->mediaDirectory->getAbsolutePath($baseTmpPath));
        if (!$result) {
            throw new \Magento\Framework\Exception\LocalizedException(
                __('File can not be saved to the destination folder.')
            );
        }
        $result['tmp_name'] = str_replace('\\', '/', $result['tmp_name']);
        $result['path'] = str_replace('\\', '/', $result['path']);
        $result['url'] = $this->storeManager
            ->getStore()
            ->getBaseUrl(
                \Magento\Framework\UrlInterface::URL_TYPE_MEDIA
            ) . $this->getFilePath($baseTmpPath, $result['file']);
        $result['name'] = $result['file'];
        if (isset($result['file'])) {
            try
            {
                $relativePath = rtrim($baseTmpPath, '/') . '/' . ltrim($result['file'], '/');
                $this->coreFileStorageDatabase->saveFile($relativePath);
            } catch (\Exception $e) {
                $this->logger->critical($e);
                throw new \Magento\Framework\Exception\LocalizedException(
                    __('Something went wrong while saving the file(s).')
                );
            }
        }
        return $result;
    }
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.