Vous pouvez créer une extension personnalisée (le nom de l'extension personnalisée est "Vendor_MyModule") pour le téléchargement d'images frontales.
Je suppose que vous avez déjà créé l'extension personnalisée "Vendor_MyModule". Je ne décris donc ici que les fichiers nécessaires liés à l'opération de téléchargement d'images.
Veuillez suivre les étapes ci-dessous.
étape 1: créez le fichier modèle de l'uploader.
app / code / Vendeur / MyMocule / Model / Upload / ImageFileUploader.php
Fichier: ImageFileUploader.php
<?php
namespace Vendor\MyModule\Model\Upload;
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
* @package Aheadworks\Rbslider\Model\Slide
*/
class ImageFileUploader
{
/**
* @var UploaderFactory
*/
private $uploaderFactory;
/**
* @var Filesystem
*/
private $filesystem;
/**
* @var StoreManagerInterface
*/
private $storeManager;
/**
* @var string
*/
const FILE_DIR = 'vendor_mymodule/uplaods';
/**
* @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'];
}
}
Étape 2: Créez le contrôleur pour télécharger l'image en utilisant le modèle créé dans setp 1
/app/code/Vendor/MyModule/Controller/Index/UploadImage.php
Fichier: UploadImage.php
namespace Vendor\MyModule\Controller\Index;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\ResultFactory;
use Vendor\MyModule\Model\Upload\ImageFileUploader;
class UploadImage extends \Magento\Framework\App\Action\Action
{
/**
* @var ImageFileUploader
*/
private $imageFileUploader;
/**
* @var \Magento\Store\Model\StoreManagerInterface
*/
protected $storeManager;
/**
* @param Context $context
* @param ImageFileUploader $imageFileUploader
*/
public function __construct(
Context $context,
\Magento\Store\Model\StoreManagerInterface $storeManager,
ImageFileUploader $imageFileUploader
) {
$this->storeManager = $storeManager;
$this->imageFileUploader = $imageFileUploader;
parent::__construct($context);
}
/**
* Image upload action
*
* @return \Magento\Framework\Controller\ResultInterface
*/
public function execute()
{
$result = $this->imageFileUploader->saveImageToMediaFolder('myimgaeupload');
return $this->resultFactory->create(ResultFactory::TYPE_JSON)->setData($result);
}
}
étape 3: créer un autre contrôleur pour charger l'application de mise en page / code / fournisseur / MuModule / Controller / Index / Index.php
Fichier: Index.php
namespace Vendor\MyModule\Controller\Index;
class Index extends \Magento\Framework\App\Action\Action
{
protected $_pageFactory;
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework\View\Result\PageFactory $pageFactory)
{
$this->_pageFactory = $pageFactory;
return parent::__construct($context);
}
public function execute()
{
$resultPage = $this->_pageFactory->create();
return $resultPage;
}
}
étape 4: Déclarez les routeurs pour votre contrôleur de fin de police.
app / code / Vendor / MyModule / etc / frontend / routes.xml
Fichier: 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="standard">
<route id="*myupload*" frontName="*myupload*">
<module name="Vendor_MyModule" />
</route>
</router>
</config>
étape 5: Déclarez layout.xml
/app/code/Vendor/MyModule//view/frontend/layout/myupload_index_index.xml
Fichier: myupload_index_index.xml
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="content">
<block class="Vendor\MyModule\Block\Myblock" name="myupload_index_index" template="Vendor_MyModule::form.phtml" />
</referenceContainer>
</body>
</page>
étape 6: créer le fichier de classe de bloc
/app/code/Vendor/MyModule/Block/Myblock.php
Fichier: Myblock.php
<?php
namespace Vendor\MyModule\Block;
class Myblock extends \Magento\Framework\View\Element\Template
{
}
étape 7: créer un fichier phtml
/app/code/Vendor/MyModule/view/frontend/templates/form.phtml
Fichier: form.phtml
<h2>Welcome to Ny Image Uploader</h2>
<div class="upload-wrapper" data-bind="scope: 'uploader'">
<!-- ko template: getTemplate() --><!-- /ko -->
</div>
<script type="text/x-magento-init">
{
".upload-wrapper": {
"Magento_Ui/js/core/app": {
"components": {
"uploader": {
"component":"Magento_Ui/js/form/element/file-uploader",
"template": "ui/form/element/uploader/uploader",
"previewTmpl":"Vendor_MyModule/checkout-image-preview",
"dataScope" : "myimgaeupload",
"uploaderConfig": {
"url": "<?php echo $block->getUrl('myupload/index/uploadimage'); ?>"
}
}
}
}
}
}
</script>
étape 8: créer un fichier de modèle KO pour l' application d' aperçu d'image
/ code / fournisseur / MyModule / view / frontend / web / template / image-preview.html
Fichier: 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>
étape 9) Exécutez les commandes CLI suivantes
sudo php bin/magento setup:di:compile
sudo rm -rf pub/static/frontend/*
sydo php bin/magento cache:flush