Magento 2 使用ui component新增後臺圖片上傳
在後端開發時我們時常根據使用者需求做出各式各樣的表單,圖片上傳也是可以使用UI component 來快速新增,支持預覽、刪除,現在就讓我們一步一步新增他。
1. 先在UI Component的fieldset新增,previewTmpl(vendor/magento/module-catalog/view/adminhtml/web/template/image-preview.html)是整個Component的HTML,可以複製並取代成你想要的樣式。
<field name="test_image" formElement="imageUploader">
<settings>
<label translate="true">Test Image</label>
<componentType>imageUploader</componentType>
<required>false</required>
</settings>
<formElements>
<imageUploader>
<settings>
<allowedExtensions>jpg jpeg gif png</allowedExtensions>
<maxFileSize>4194304</maxFileSize>
<previewTmpl>Magento_Catalog/image-preview</previewTmpl>
<uploaderConfig>
<param xsi:type="string" name="url">test/Image/save</param>
</uploaderConfig>
</settings>
</imageUploader>
</formElements>
</field>
2. 接下來要做出存圖片的地方,先新增route
app/code/AstralWeb/Test/etc/adminhtml/routes.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="admin">
<route id="test" frontName="test">
<module name="AstralWeb_Test" />
</route>
</router>
</config>
3. app/code/AstralWeb/Test/etc/di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<virtualType name="AstralwebTestImageUploader" type="Magento\Catalog\Model\ImageUploader">
<arguments>
<argument name="baseTmpPath" xsi:type="string">logo/image</argument>
<argument name="basePath" xsi:type="string">logo/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="Astralweb\Test\Controller\Adminhtml\Image\Save">
<arguments>
<argument name="imageUploader" xsi:type="object">AstralwebTestImageUploader</argument>
</arguments>
</type>
</config>
app/code/AstralWeb/Test/Controller/Adminhtml/Image/Save.php
<?php
namespace AstralWeb\Test\Controller\Adminhtml\Image;
use Exception;
use Magento\Catalog\Model\ImageUploader;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\Controller\ResultInterface;
class Save extends Action implements HttpPostActionInterface
{
/**
* Image uploader
*
* @var ImageUploader
*/
protected $imageUploader;
/**
* @var array|mixed
*/
protected $imageParamName;
/**
* Save constructor.
* @param Context $context
* @param ImageUploader $imageUploader
* @param array $imageParamName
*/
public function __construct(
Context $context,
ImageUploader $imageUploader,
$imageParamName = []
) {
parent::__construct($context);
$this->imageUploader = $imageUploader;
$this->imageParamName = $imageParamName;
}
/**
* Upload file controller action
*
* @return ResultInterface
*/
public function execute()
{
foreach ($this->imageParamName as $param){
$imageId = $this->_request->getParam('param_name', $param);
}
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);
}
}
最後別忘了你得 DataProvider 在Image的輸出,要改成陣列,要不然有圖片Javascript會出 Uncaught TypeError: value.map is not a function 的錯誤。
$items = $this->collection->getItems();
foreach ($items as $itemData) {
$this->loadedData[$item->getId()] = $item->getData();
}
$this->loadedData[$item->getId()]['test_image'] = [
'name' => $itemData->getData($param),
'url' => $this->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) . 'logo/image' . $itemData['logo'],
'size' => filesize(
$this->filesystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath(
'logo/image' . $itemData['logo']
))
]
到這邊我們就使用ui component增加了圖片上傳功能,實際上它處理了很多的東西,讓我們在開發後臺時方便很多。
參考資料:
https://developer.adobe.com/commerce/frontend-core/ui-components/components/file-uploader
以上就是歐斯瑞本次 『Magento 2 使用ui component新增後臺圖片上傳』 分享,接下來還會持續介紹各種簡易又好用的方法給大家喔!
我要留言