Magento 2.3.0 Custom UI Component custom admin form How to Upload image? The Next CEO of Stack OverflowMagento2 : Admin module Image upload code to display formMagento 2 : Added field for image upload in admin formMagento 2 : Image upload field in admin form using ui componentupload custom product image programaticallyMagento 2.1 UI Component Image upload formAdding image upload field to admin formSelect and upload image admin form magento 2Magento 2.3.0 - Transactional Email > Logo Image upload not workingCan't upload logo file Magento 2.3.0Magento 2.3 : Multiple image upload in admin form ui component?
Can the Reverse Gravity spell affect the Meteor Swarm spell?
Visit to the USA with ESTA approved before trip to Iran
Grabbing quick drinks
Why doesn't a table tennis ball float on the surface? How do we calculate buoyancy here?
What is the purpose of the Evocation wizard's Potent Cantrip feature?
Why here is plural "We went to the movies last night."
Are there languages with no euphemisms?
How to write the block matrix in LaTex?
Anatomically Correct Strange Women In Ponds Distributing Swords
Why do professional authors make "consistency" mistakes? And how to avoid them?
When airplanes disconnect from a tanker during air to air refueling, why do they bank so sharply to the right?
How can I open an app using Terminal?
How easy is it to start Magic from scratch?
I believe this to be a fraud - hired, then asked to cash check and send cash as Bitcoin
What is the difference between "behavior" and "behaviour"?
Can a single photon have an energy density?
How can I get through very long and very dry, but also very useful technical documents when learning a new tool?
Why were Madagascar and New Zealand discovered so late?
How do we know the LHC results are robust?
Anatomically Correct Mesopelagic Aves
Why does standard notation not preserve intervals (visually)
Unreliable Magic - Is it worth it?
Can I equip Skullclamp on a creature I am sacrificing?
Does it take more energy to get to Venus or to Mars?
Magento 2.3.0 Custom UI Component custom admin form How to Upload image?
The Next CEO of Stack OverflowMagento2 : Admin module Image upload code to display formMagento 2 : Added field for image upload in admin formMagento 2 : Image upload field in admin form using ui componentupload custom product image programaticallyMagento 2.1 UI Component Image upload formAdding image upload field to admin formSelect and upload image admin form magento 2Magento 2.3.0 - Transactional Email > Logo Image upload not workingCan't upload logo file Magento 2.3.0Magento 2.3 : Multiple image upload in admin form ui component?
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
CirklestudioCustomproductControllerAdminhtmlCustomoptionUpload.php
<?php
namespace CirklestudioCustomproductControllerAdminhtmlCustomoption;
use MagentoFrameworkControllerResultFactory;
/** * Class Upload */
class Upload extends MagentoBackendAppAction
/**
* Image uploader *
* @var MagentoCatalogModelImageUploader */ protected $imageUploader;
/**
* Upload constructor.
*
* @param MagentoBackendAppActionContext $context
* @param MagentoCatalogModelImageUploader $imageUploader
*/
public function __construct(
MagentoBackendAppActionContext $context,
CirklestudioCustomproductModelImageUploader $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 MagentoFrameworkControllerResultInterface
*/
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)
CirklestudioCustomproductModelImageUploader.php
<?php
/**
* Simple Hello World Module
** @category QaisarSatti
* @package QaisarSatti_HelloWorld
* @author Muhammad Qaisar Satti
* @Email qaisarssatti@gmail.com * */
namespace CirklestudioCustomproductModel;
/**
* Catalog image uploader */
class ImageUploader
/**
* Core file storage database
*
* @var MagentoMediaStorageHelperFileStorageDatabase */
protected $coreFileStorageDatabase;
/**
* Media directory object (writable).
*
* @var MagentoFrameworkFilesystemDirectoryWriteInterface
*/
protected $mediaDirectory;
/**
* Uploader factory
*
* @var MagentoMediaStorageModelFileUploaderFactory
*/
private $uploaderFactory;
/**
* Store manager
*
* @var MagentoStoreModelStoreManagerInterface
*/
protected $storeManager;
/**
* @var PsrLogLoggerInterface
*/
protected $logger;
/**
* Base tmp path
*
* @var string
*/
protected $baseTmpPath;
/**
* Base path
*
* @var string
*/
protected $basePath;
/**
* Allowed extensions
*
* @var string
*/
protected $allowedExtensions;
/**
* ImageUploader constructor
*
* @param MagentoMediaStorageHelperFileStorageDatabase $coreFileStorageDatabase
* @param MagentoFrameworkFilesystem $filesystem
* @param MagentoMediaStorageModelFileUploaderFactory $uploaderFactory
* @param MagentoStoreModelStoreManagerInterface $storeManager
* @param PsrLogLoggerInterface $logger
* @param string $baseTmpPath
* @param string $basePath
* @param string[] $allowedExtensions
*/
public function __construct(
MagentoMediaStorageHelperFileStorageDatabase $coreFileStorageDatabase,
MagentoFrameworkFilesystem $filesystem,
MagentoMediaStorageModelFileUploaderFactory $uploaderFactory,
MagentoStoreModelStoreManagerInterface $storeManager,
PsrLogLoggerInterface $logger,
$baseTmpPath,
$basePath,
$allowedExtensions
)
$this->coreFileStorageDatabase = $coreFileStorageDatabase;
$this->mediaDirectory = $filesystem->getDirectoryWrite(MagentoFrameworkAppFilesystemDirectoryList::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 MagentoFrameworkExceptionLocalizedException
*/
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 MagentoFrameworkExceptionLocalizedException(
__('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 MagentoFrameworkExceptionLocalizedException
*/
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 MagentoFrameworkExceptionLocalizedException(
__('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(
MagentoFrameworkUrlInterface::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 MagentoFrameworkExceptionLocalizedException(
__('Something went wrong while saving the file(s).')
);
return $result;
di.xml
<virtualType name="CirklestudioCustomproductCustomproductImageUpload" type="CirklestudioCustomproductModelImageUploader">
<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="CirklestudioCustomproductControllerAdminhtmlCustomoptionUpload">
<arguments>
<argument name="imageUploader" xsi:type="object">CirklestudioCustomproductCustomproductImageUpload</argument>
</arguments>
</type>
image-upload magento2.3.0
add a comment |
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
CirklestudioCustomproductControllerAdminhtmlCustomoptionUpload.php
<?php
namespace CirklestudioCustomproductControllerAdminhtmlCustomoption;
use MagentoFrameworkControllerResultFactory;
/** * Class Upload */
class Upload extends MagentoBackendAppAction
/**
* Image uploader *
* @var MagentoCatalogModelImageUploader */ protected $imageUploader;
/**
* Upload constructor.
*
* @param MagentoBackendAppActionContext $context
* @param MagentoCatalogModelImageUploader $imageUploader
*/
public function __construct(
MagentoBackendAppActionContext $context,
CirklestudioCustomproductModelImageUploader $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 MagentoFrameworkControllerResultInterface
*/
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)
CirklestudioCustomproductModelImageUploader.php
<?php
/**
* Simple Hello World Module
** @category QaisarSatti
* @package QaisarSatti_HelloWorld
* @author Muhammad Qaisar Satti
* @Email qaisarssatti@gmail.com * */
namespace CirklestudioCustomproductModel;
/**
* Catalog image uploader */
class ImageUploader
/**
* Core file storage database
*
* @var MagentoMediaStorageHelperFileStorageDatabase */
protected $coreFileStorageDatabase;
/**
* Media directory object (writable).
*
* @var MagentoFrameworkFilesystemDirectoryWriteInterface
*/
protected $mediaDirectory;
/**
* Uploader factory
*
* @var MagentoMediaStorageModelFileUploaderFactory
*/
private $uploaderFactory;
/**
* Store manager
*
* @var MagentoStoreModelStoreManagerInterface
*/
protected $storeManager;
/**
* @var PsrLogLoggerInterface
*/
protected $logger;
/**
* Base tmp path
*
* @var string
*/
protected $baseTmpPath;
/**
* Base path
*
* @var string
*/
protected $basePath;
/**
* Allowed extensions
*
* @var string
*/
protected $allowedExtensions;
/**
* ImageUploader constructor
*
* @param MagentoMediaStorageHelperFileStorageDatabase $coreFileStorageDatabase
* @param MagentoFrameworkFilesystem $filesystem
* @param MagentoMediaStorageModelFileUploaderFactory $uploaderFactory
* @param MagentoStoreModelStoreManagerInterface $storeManager
* @param PsrLogLoggerInterface $logger
* @param string $baseTmpPath
* @param string $basePath
* @param string[] $allowedExtensions
*/
public function __construct(
MagentoMediaStorageHelperFileStorageDatabase $coreFileStorageDatabase,
MagentoFrameworkFilesystem $filesystem,
MagentoMediaStorageModelFileUploaderFactory $uploaderFactory,
MagentoStoreModelStoreManagerInterface $storeManager,
PsrLogLoggerInterface $logger,
$baseTmpPath,
$basePath,
$allowedExtensions
)
$this->coreFileStorageDatabase = $coreFileStorageDatabase;
$this->mediaDirectory = $filesystem->getDirectoryWrite(MagentoFrameworkAppFilesystemDirectoryList::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 MagentoFrameworkExceptionLocalizedException
*/
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 MagentoFrameworkExceptionLocalizedException(
__('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 MagentoFrameworkExceptionLocalizedException
*/
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 MagentoFrameworkExceptionLocalizedException(
__('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(
MagentoFrameworkUrlInterface::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 MagentoFrameworkExceptionLocalizedException(
__('Something went wrong while saving the file(s).')
);
return $result;
di.xml
<virtualType name="CirklestudioCustomproductCustomproductImageUpload" type="CirklestudioCustomproductModelImageUploader">
<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="CirklestudioCustomproductControllerAdminhtmlCustomoptionUpload">
<arguments>
<argument name="imageUploader" xsi:type="object">CirklestudioCustomproductCustomproductImageUpload</argument>
</arguments>
</type>
image-upload magento2.3.0
show your code that you have tried.
– Manashvi Birla
yesterday
Please check code
– Hardik Makwana
yesterday
try using this instead of fileUploader<item name="formElement" xsi:type="string">imageUploader</item>
– Ghulam.M
yesterday
I tried but not working same error occured "The file was not uploaded"
– Hardik Makwana
22 hours ago
add a comment |
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
CirklestudioCustomproductControllerAdminhtmlCustomoptionUpload.php
<?php
namespace CirklestudioCustomproductControllerAdminhtmlCustomoption;
use MagentoFrameworkControllerResultFactory;
/** * Class Upload */
class Upload extends MagentoBackendAppAction
/**
* Image uploader *
* @var MagentoCatalogModelImageUploader */ protected $imageUploader;
/**
* Upload constructor.
*
* @param MagentoBackendAppActionContext $context
* @param MagentoCatalogModelImageUploader $imageUploader
*/
public function __construct(
MagentoBackendAppActionContext $context,
CirklestudioCustomproductModelImageUploader $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 MagentoFrameworkControllerResultInterface
*/
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)
CirklestudioCustomproductModelImageUploader.php
<?php
/**
* Simple Hello World Module
** @category QaisarSatti
* @package QaisarSatti_HelloWorld
* @author Muhammad Qaisar Satti
* @Email qaisarssatti@gmail.com * */
namespace CirklestudioCustomproductModel;
/**
* Catalog image uploader */
class ImageUploader
/**
* Core file storage database
*
* @var MagentoMediaStorageHelperFileStorageDatabase */
protected $coreFileStorageDatabase;
/**
* Media directory object (writable).
*
* @var MagentoFrameworkFilesystemDirectoryWriteInterface
*/
protected $mediaDirectory;
/**
* Uploader factory
*
* @var MagentoMediaStorageModelFileUploaderFactory
*/
private $uploaderFactory;
/**
* Store manager
*
* @var MagentoStoreModelStoreManagerInterface
*/
protected $storeManager;
/**
* @var PsrLogLoggerInterface
*/
protected $logger;
/**
* Base tmp path
*
* @var string
*/
protected $baseTmpPath;
/**
* Base path
*
* @var string
*/
protected $basePath;
/**
* Allowed extensions
*
* @var string
*/
protected $allowedExtensions;
/**
* ImageUploader constructor
*
* @param MagentoMediaStorageHelperFileStorageDatabase $coreFileStorageDatabase
* @param MagentoFrameworkFilesystem $filesystem
* @param MagentoMediaStorageModelFileUploaderFactory $uploaderFactory
* @param MagentoStoreModelStoreManagerInterface $storeManager
* @param PsrLogLoggerInterface $logger
* @param string $baseTmpPath
* @param string $basePath
* @param string[] $allowedExtensions
*/
public function __construct(
MagentoMediaStorageHelperFileStorageDatabase $coreFileStorageDatabase,
MagentoFrameworkFilesystem $filesystem,
MagentoMediaStorageModelFileUploaderFactory $uploaderFactory,
MagentoStoreModelStoreManagerInterface $storeManager,
PsrLogLoggerInterface $logger,
$baseTmpPath,
$basePath,
$allowedExtensions
)
$this->coreFileStorageDatabase = $coreFileStorageDatabase;
$this->mediaDirectory = $filesystem->getDirectoryWrite(MagentoFrameworkAppFilesystemDirectoryList::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 MagentoFrameworkExceptionLocalizedException
*/
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 MagentoFrameworkExceptionLocalizedException(
__('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 MagentoFrameworkExceptionLocalizedException
*/
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 MagentoFrameworkExceptionLocalizedException(
__('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(
MagentoFrameworkUrlInterface::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 MagentoFrameworkExceptionLocalizedException(
__('Something went wrong while saving the file(s).')
);
return $result;
di.xml
<virtualType name="CirklestudioCustomproductCustomproductImageUpload" type="CirklestudioCustomproductModelImageUploader">
<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="CirklestudioCustomproductControllerAdminhtmlCustomoptionUpload">
<arguments>
<argument name="imageUploader" xsi:type="object">CirklestudioCustomproductCustomproductImageUpload</argument>
</arguments>
</type>
image-upload magento2.3.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
CirklestudioCustomproductControllerAdminhtmlCustomoptionUpload.php
<?php
namespace CirklestudioCustomproductControllerAdminhtmlCustomoption;
use MagentoFrameworkControllerResultFactory;
/** * Class Upload */
class Upload extends MagentoBackendAppAction
/**
* Image uploader *
* @var MagentoCatalogModelImageUploader */ protected $imageUploader;
/**
* Upload constructor.
*
* @param MagentoBackendAppActionContext $context
* @param MagentoCatalogModelImageUploader $imageUploader
*/
public function __construct(
MagentoBackendAppActionContext $context,
CirklestudioCustomproductModelImageUploader $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 MagentoFrameworkControllerResultInterface
*/
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)
CirklestudioCustomproductModelImageUploader.php
<?php
/**
* Simple Hello World Module
** @category QaisarSatti
* @package QaisarSatti_HelloWorld
* @author Muhammad Qaisar Satti
* @Email qaisarssatti@gmail.com * */
namespace CirklestudioCustomproductModel;
/**
* Catalog image uploader */
class ImageUploader
/**
* Core file storage database
*
* @var MagentoMediaStorageHelperFileStorageDatabase */
protected $coreFileStorageDatabase;
/**
* Media directory object (writable).
*
* @var MagentoFrameworkFilesystemDirectoryWriteInterface
*/
protected $mediaDirectory;
/**
* Uploader factory
*
* @var MagentoMediaStorageModelFileUploaderFactory
*/
private $uploaderFactory;
/**
* Store manager
*
* @var MagentoStoreModelStoreManagerInterface
*/
protected $storeManager;
/**
* @var PsrLogLoggerInterface
*/
protected $logger;
/**
* Base tmp path
*
* @var string
*/
protected $baseTmpPath;
/**
* Base path
*
* @var string
*/
protected $basePath;
/**
* Allowed extensions
*
* @var string
*/
protected $allowedExtensions;
/**
* ImageUploader constructor
*
* @param MagentoMediaStorageHelperFileStorageDatabase $coreFileStorageDatabase
* @param MagentoFrameworkFilesystem $filesystem
* @param MagentoMediaStorageModelFileUploaderFactory $uploaderFactory
* @param MagentoStoreModelStoreManagerInterface $storeManager
* @param PsrLogLoggerInterface $logger
* @param string $baseTmpPath
* @param string $basePath
* @param string[] $allowedExtensions
*/
public function __construct(
MagentoMediaStorageHelperFileStorageDatabase $coreFileStorageDatabase,
MagentoFrameworkFilesystem $filesystem,
MagentoMediaStorageModelFileUploaderFactory $uploaderFactory,
MagentoStoreModelStoreManagerInterface $storeManager,
PsrLogLoggerInterface $logger,
$baseTmpPath,
$basePath,
$allowedExtensions
)
$this->coreFileStorageDatabase = $coreFileStorageDatabase;
$this->mediaDirectory = $filesystem->getDirectoryWrite(MagentoFrameworkAppFilesystemDirectoryList::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 MagentoFrameworkExceptionLocalizedException
*/
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 MagentoFrameworkExceptionLocalizedException(
__('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 MagentoFrameworkExceptionLocalizedException
*/
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 MagentoFrameworkExceptionLocalizedException(
__('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(
MagentoFrameworkUrlInterface::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 MagentoFrameworkExceptionLocalizedException(
__('Something went wrong while saving the file(s).')
);
return $result;
di.xml
<virtualType name="CirklestudioCustomproductCustomproductImageUpload" type="CirklestudioCustomproductModelImageUploader">
<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="CirklestudioCustomproductControllerAdminhtmlCustomoptionUpload">
<arguments>
<argument name="imageUploader" xsi:type="object">CirklestudioCustomproductCustomproductImageUpload</argument>
</arguments>
</type>
image-upload magento2.3.0
image-upload magento2.3.0
edited yesterday
Ghulam.M
17811
17811
asked yesterday
Hardik MakwanaHardik Makwana
959
959
show your code that you have tried.
– Manashvi Birla
yesterday
Please check code
– Hardik Makwana
yesterday
try using this instead of fileUploader<item name="formElement" xsi:type="string">imageUploader</item>
– Ghulam.M
yesterday
I tried but not working same error occured "The file was not uploaded"
– Hardik Makwana
22 hours ago
add a comment |
show your code that you have tried.
– Manashvi Birla
yesterday
Please check code
– Hardik Makwana
yesterday
try using this instead of fileUploader<item name="formElement" xsi:type="string">imageUploader</item>
– Ghulam.M
yesterday
I tried but not working same error occured "The file was not uploaded"
– Hardik Makwana
22 hours ago
show your code that you have tried.
– Manashvi Birla
yesterday
show your code that you have tried.
– Manashvi Birla
yesterday
Please check code
– Hardik Makwana
yesterday
Please check code
– Hardik Makwana
yesterday
try using this instead of fileUploader
<item name="formElement" xsi:type="string">imageUploader</item>
– Ghulam.M
yesterday
try using this instead of fileUploader
<item name="formElement" xsi:type="string">imageUploader</item>
– Ghulam.M
yesterday
I tried but not working same error occured "The file was not uploaded"
– Hardik Makwana
22 hours ago
I tried but not working same error occured "The file was not uploaded"
– Hardik Makwana
22 hours ago
add a comment |
0
active
oldest
votes
Your Answer
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "479"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f267574%2fmagento-2-3-0-custom-ui-component-custom-admin-form-how-to-upload-image%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Magento Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f267574%2fmagento-2-3-0-custom-ui-component-custom-admin-form-how-to-upload-image%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
show your code that you have tried.
– Manashvi Birla
yesterday
Please check code
– Hardik Makwana
yesterday
try using this instead of fileUploader
<item name="formElement" xsi:type="string">imageUploader</item>
– Ghulam.M
yesterday
I tried but not working same error occured "The file was not uploaded"
– Hardik Makwana
22 hours ago