נתיב: Abra/HeaderLink/view/adminhtml/ui_component/abra_headerlink_linkitem_form.xml
<field name="icon" formElement="imageUploader">
<settings>
<notice translate="true">Some notice.</notice>
<label translate="true">Image Uploader Example</label>
<componentType>imageUploader</componentType>
</settings>
<formElements>
<imageUploader>
<settings>
<allowedExtensions>jpg jpeg gif png</allowedExtensions>
<maxFileSize>2097152</maxFileSize>
<uploaderConfig>
<param xsi:type="string" name="url">abra_headerlink/image/upload</param>
</uploaderConfig>
</settings>
</imageUploader>
</formElements>
</field>
נתיב : Abra/HeaderLink/Controller/Adminhtml/Image/Upload.php
*לשנות שמות
ומשתנה :
$imageId = $this->_request->getParam('param_name', 'title');
<?php
namespace Abra\HeaderLink\Controller\Adminhtml\Image;
use Exception;
use Abra\HeaderLink\Model\ImageUploader;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\Controller\ResultInterface;
class Upload extends Action
{
/**
* Image uploader
*
* @var ImageUploader
*/
protected $imageUploader;
/**
* Upload constructor.
*
* @param Context $context
* @param ImageUploader $imageUploader
*/
public function __construct(
Context $context,
ImageUploader $imageUploader
)
{
parent::__construct($context);
$this->imageUploader = $imageUploader;
}
/**
* Upload file controller action
*
* @return ResultInterface
*/
public function execute()
{
$imageId = $this->_request->getParam('param_name', 'icon');
try {
$result = $this->imageUploader->saveFileToTmpDir($imageId);
} catch (Exception $e) {
$result = ['error' => $e->getMessage(), 'errorcode' => $e->getCode()];
}
return $this->resultFactory->create(ResultFactory::TYPE_JSON)->setData($result);
}
}
נתיב: Abra/IconUploud/Model/ImageUploader.php
<?php
namespace Abra\IconUploud\Model;
use Exception;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Exception\FileSystemException;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\File\Uploader;
use Magento\Framework\Filesystem;
use Magento\Framework\Filesystem\Directory\WriteInterface;
use Magento\Framework\UrlInterface;
use Magento\MediaStorage\Helper\File\Storage\Database;
use Magento\MediaStorage\Model\File\UploaderFactory;
use Magento\Store\Model\StoreManagerInterface;
use Psr\Log\LoggerInterface;
class ImageUploader
{
const IMAGE_TMP_PATH = 'headerlink/tmp/icon';
const IMAGE_PATH = 'headerlink/icon';
/**
* Core file storage database
*
* @var Database
*/
protected $coreFileStorageDatabase;
/**
* Media directory object (writable).
*
* @var WriteInterface
*/
protected $mediaDirectory;
/**
* Uploader factory
*
* @var UploaderFactory
*/
protected $uploaderFactory;
/**
* Store manager
*
* @var StoreManagerInterface
*/
protected $storeManager;
/**
* @var LoggerInterface
*/
protected $logger;
/**
* Base tmp path
*
* @var string
*/
protected $baseTmpPath;
/**
* Base path
*
* @var string
*/
protected $basePath;
/**
* Allowed extensions
*
* @var string
*/
protected $allowedExtensions;
/**
* List of allowed image mime types
*
* @var string[]
*/
protected $allowedMimeTypes;
/**
* ImageUploader constructor
*
* @param Database $coreFileStorageDatabase
* @param Filesystem $filesystem
* @param UploaderFactory $uploaderFactory
* @param StoreManagerInterface $storeManager
* @param LoggerInterface $logger
* @param string $baseTmpPath
* @param string $basePath
* @param string[] $allowedExtensions
* @param string[] $allowedMimeTypes
* @throws FileSystemException
*/
public function __construct(
Database $coreFileStorageDatabase,
Filesystem $filesystem,
UploaderFactory $uploaderFactory,
StoreManagerInterface $storeManager,
LoggerInterface $logger,
$baseTmpPath = self::IMAGE_TMP_PATH,
$basePath = self::IMAGE_PATH,
$allowedExtensions = [],
$allowedMimeTypes = []
)
{
$this->coreFileStorageDatabase = $coreFileStorageDatabase;
$this->mediaDirectory = $filesystem->getDirectoryWrite(DirectoryList::MEDIA);
$this->uploaderFactory = $uploaderFactory;
$this->storeManager = $storeManager;
$this->logger = $logger;
$this->baseTmpPath = $baseTmpPath;
$this->basePath = $basePath;
$this->allowedExtensions = $allowedExtensions;
$this->allowedMimeTypes = $allowedMimeTypes;
}
/**
* 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()
{
$this->logger->error('getBaseTmpPath: '. $this->baseTmpPath);
return $this->baseTmpPath;
}
/**
* Retrieve base path
*
* @return string
*/
public function getBasePath()
{
return $this->basePath;
}
/**
* Retrieve allowed extensions
*
* @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 LocalizedException
*/
public function moveFileFromTmp($imageName)
{
$baseTmpPath = $this->getBaseTmpPath();
$basePath = $this->getBasePath();
$baseImagePath = $this->getFilePath(
$basePath,
Uploader::getNewFileName(
$this->mediaDirectory->getAbsolutePath(
$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 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 LocalizedException
*/
public function saveFileToTmpDir($fileId)
{
$baseTmpPath = $this->getBaseTmpPath();
$this->logger->error('save to temp: '.$baseTmpPath);
/** @var \Magento\MediaStorage\Model\File\Uploader $uploader */
$uploader = $this->uploaderFactory->create(['fileId' => $fileId]);
$uploader->setAllowedExtensions($this->getAllowedExtensions());
$uploader->setAllowRenameFiles(true);
if (!$uploader->checkMimeType($this->allowedMimeTypes)) {
throw new LocalizedException(__('File validation failed.'));
}
$result = $uploader->save($this->mediaDirectory->getAbsolutePath($baseTmpPath));
unset($result['path']);
if (!$result) {
throw new 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['url'] = $this->storeManager
->getStore()
->getBaseUrl(
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 LocalizedException(
__('Something went wrong while saving the file(s).')
);
}
}
return $result;
}
}
<!-- Image Uploader -->
<virtualType name="Abra\HeaderLink\ReferenceImageUpload" type="Abra\HeaderLink\Model\ImageUploader">
<arguments>
<argument name="baseTmpPath" xsi:type="string">headerlink/tmp/image</argument>
<argument name="basePath" xsi:type="string">headerlink/image</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="Abra\HeaderLink\Controller\Adminhtml\Image\Upload">
<arguments>
<argument name="imageUploader" xsi:type="object">Abra\HeaderLink\ReferenceImageUpload</argument>
</arguments>
</type>
<type name="Abra\HeaderLink\Controller\Adminhtml\LinkItem\Save">
<arguments>
<argument name="imageUploader" xsi:type="object">Abra\HeaderLink\ReferenceImageUpload</argument>
</arguments>
</type>
<!-- End Image Uploader -->
</config>