如何在前端重新创建Magento 2后端图像上传


15

在Magento 2中,有一个图像上传器,如下所示:

在此处输入图片说明

它将使用AJAX上传图片,并返回序列化的JSON,其中包含上传的图片信息。有没有办法在前端phtml文件中重新创建此功能?


我没有尝试过,但是您可以检查管理模块是否相同,以在前端获得实现的想法。
Jai

Answers:


2

您可以创建用于前端图像上传的自定义扩展名(让自定义扩展名为“ Vendor_MyModule”)。

我假设您已经创建了自定义扩展“ Vendor_MyModule”。因此,我在这里仅描述与图像上传操作有关的必要文件。

请按照以下步骤操作。

步骤1:创建上传器模型文件。 应用程序/代码/供应商/ MyMocule /模型/上传/ImageFileUploader.php

档案: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'];
    }
}

步骤2:使用setp 1中创建的模型创建控制器以上传图像

/app/code/Vendor/MyModule/Controller/Index/UploadImage.php

档案: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);
    }
}

步骤3:创建另一个控制器以加载布局应用程序/代码/供应商/MuModule/Controller/Index/Index.php

文件: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; 
}

}

第4步:为字体结束控制器声明路由器。 app / code / Vendor / MyModule / etc / frontend / routes.xml

文件: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>

步骤5:声明layout.xml /app/code/Vendor/MyModule//view/frontend/layout/myupload_index_index.xml

文件: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>

第6步:创建块类文件 /app/code/Vendor/MyModule/Block/Myblock.php

文件:Myblock.php

<?php

namespace Vendor\MyModule\Block;


class Myblock  extends \Magento\Framework\View\Element\Template
{


}

步骤7:建立phtml档案

/app/code/Vendor/MyModule/view/frontend/templates/form.phtml

文件: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> 

第8步:为图像预览应用程序/代码/供应商/MyModule/view/frontend/web/template/image-preview.html创建KO模板文件

文件: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>

步骤9)运行以下CLI命令

sudo php bin/magento setup:di:compile
sudo rm -rf pub/static/frontend/*
sydo php bin/magento cache:flush

在此处输入图片说明

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.