0

I'm using this code to upload images to a custom field in the admin panel:

 <item name="config" xsi:type="array">
 <item name="dataType" xsi:type="string">string</item>
 <item name="source" xsi:type="string">page</item>
 <item name="label" xsi:type="string" translate="true">Hero 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">Company_CmsPage/image-preview</item>
 <item name="required" xsi:type="boolean">false</item>
 <item name="uploaderConfig" xsi:type="array">
 <item name="url" xsi:type="url" path="Company_CmsPage/hero_image/upload"/>
 </item>
 </item>

When images are uploaded I get the following error: A technical problem with the server created an error. Try again to continue what you were doing. If the problem persists, try again later.

Here is controller code Controller/Adminhtml/Cms/Upload.php

namespace ISM\CmsPage\Controller\Adminhtml\Cms\Heroimage;
use Magento\Framework\Controller\ResultFactory;
class Upload extends \Magento\Backend\App\Action
{
 /**
 * Image uploader
 *
 * @var \[Vendor]\[Module]\Model\ImageUploader
 */
 protected $imageUploader;
 /**
 * @param \Magento\Backend\App\Action\Context $context
 * @param \Magento\Catalog\Model\ImageUploader $imageUploader
 */
 public function __construct(
 \Magento\Backend\App\Action\Context $context,
 \Magento\Catalog\Model\ImageUploader $imageUploader
 ) {
 parent::__construct($context);
 $this->imageUploader = $imageUploader;
 }
 /**
 * Upload file controller action
 *
 * @return \Magento\Framework\Controller\ResultInterface
 */
 public function execute()
 {
 try {
 $result = $this->imageUploader->saveFileToTmpDir('hero_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);
 }
}
?>

I've checked Magento and Server logs but haven't found anything.

asked Jun 25, 2020 at 7:47

1 Answer 1

0

You did not provide your controller code for image uploading. However I am providing two files. One is model file for uplaoding and another one is a controller.

Step 1)

Create the file ImageFileUploader.php under app/code/Company/CmsPage/Model/

Please change following const as per your preference

const FILE_DIR = 'hero_image/banner';

File : app/code/Company/CmsPage/Model/ImageFileUploader.php

<?php
namespace Company\CmsPage\Model;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Filesystem;
use Magento\MediaStorage\Model\File\UploaderFactory;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\UrlInterface;
use Magento\Store\Model\StoreManagerInterface;
 
class ImageFileUploader
{
 /**
 * @var UploaderFactory
 */
 private $uploaderFactory;
 /**
 * @var Filesystem
 */
 private $filesystem;
 /**
 * @var StoreManagerInterface
 */
 private $storeManager;
 /**
 * @var string
 */
 const FILE_DIR = 'hero_image/banner';
 /**
 * @param UploaderFactory $uploaderFactory
 * @param Filesystem $filesystem
 * @param StoreManagerInterface $storeManager
 */
 public function __construct(
 UploaderFactory $uploaderFactory,
 Filesystem $filesystem,
 StoreManagerInterface $storeManager
 ) {
 $this->uploaderFactory = $uploaderFactory;
 $this->storeManager = $storeManager;
 $this->filesystem = $filesystem;
 }
 /**
 * Save file to temp media directory
 *
 * @param string $fileId
 * @return array
 * @throws LocalizedException
 */
 public function saveImageToMediaFolder($fileId)
 {
 try {
 $result = ['file' => '', 'size' => ''];
 /** @var \Magento\Framework\Filesystem\Directory\Read $mediaDirectory */
 $mediaDirectory = $this->filesystem
 ->getDirectoryRead(DirectoryList::MEDIA)
 ->getAbsolutePath(self::FILE_DIR);
 /** @var \Magento\MediaStorage\Model\File\Uploader $uploader */
 $uploader = $this->uploaderFactory->create(['fileId' => $fileId]);
 $uploader->setAllowRenameFiles(true);
 $uploader->setFilesDispersion(false);
 $uploader->setAllowedExtensions($this->getAllowedExtensions());
 $result = array_intersect_key($uploader->save($mediaDirectory), $result);
 $result['url'] = $this->getMediaUrl($result['file']);
 } catch (\Exception $e) {
 $result = ['error' => $e->getMessage(), 'errorcode' => $e->getCode()];
 }
 return $result;
 }
 /**
 * Get file url
 *
 * @param string $file
 * @return string
 */
 public function getMediaUrl($file)
 {
 $file = ltrim(str_replace('\\', '/', $file), '/');
 return $this->storeManager
 ->getStore()
 ->getBaseUrl(UrlInterface::URL_TYPE_MEDIA) . self::FILE_DIR . '/' . $file;
 }
 /**
 * Get allowed file extensions
 *
 * @return string[]
 */
 public function getAllowedExtensions()
 {
 return ['jpg', 'jpeg', 'gif', 'png'];
 }
}

step 2)

create (or update exiting Controller) file UploadImage.php under app/code/Company/CmsPage/Controller/Adminhtml/Index/

File : app/code/Company/CmsPage/Controller/Adminhtml/Index/UploadImage.php

<?php
namespace Company\CmsPage\Controller\Adminhtml\Index;
................
................
................
use Magento\Framework\Controller\ResultFactory;
use Company\CmsPage\Model\ImageFileUploader;
/**
 * Class UploadImage
 * @package Aheadworks\Rbslider\Controller\Adminhtml\Slide
 */
class UploadImage extends \Magento\Backend\App\Action
{
 
 ................
 ................
 ................
 /**
 * @var ImageFileUploader
 */
 private $imageFileUploader;
 /**
 * @param Context $context
 * @param ImageFileUploader $imageFileUploader
 */
 public function __construct(
 ................,
 ................,
 ................,
 ImageFileUploader $imageFileUploader
 ) {
 parent::__construct($context);
 ................
 ................
 $this->imageFileUploader = $imageFileUploader;
 }
 /**
 * Image upload action
 *
 * @return \Magento\Framework\Controller\ResultInterface
 */
 public function execute()
 {
 $result = $this->imageFileUploader->saveImageToMediaFolder('img_file');
 return $this->resultFactory->create(ResultFactory::TYPE_JSON)->setData($result);
 }
}

step : 3 Run php bin/magento setup:di:compile

Note : make sure url part of your UI xml match with the controller file

<item name="uploaderConfig" xsi:type="array">
<item name="url" xsi:type="url" path="Company_CmsPage/hero_image/upload"/>
</item>
answered Jun 25, 2020 at 12:43
3
  • Followed directions, still getting error. Does the path need to be an existing directory? What is it relative to. Should it have special permissions? Commented Jun 25, 2020 at 17:10
  • which path did you mean? Image upload folder path? No image upload path (i.e. "pub/media/hero_image/banner") does not need special permission. Can you log some date on admin image uploader controller to confirm the controller is calling . Commented Jun 26, 2020 at 7:52
  • Controller/Adminhtml/Cms/Upload.php I added to the question. Commented Jun 26, 2020 at 8:55

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.