0

I have created a customer attribute called the customer logo and I want to get URL of that customer logo in the Email I am trying to access using but it gives 404

https://localhost/pub/media/customer/A/P/demo.png

So is there any way like we can get the proper URL of the customer upload file? and that's direct accessible everywhere like a display in email etc

0

Try below code

app/code/Vendorname/Modulename/etc/frontend/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="routename">
            <module name="Vendorname_Modulename" />
        </route>
    </router>
</config>

app/code/Vendorname/Modulename/Block/Logo.php

<?php

namespace Vendorname\Modulename\Block;

use Magento\Framework\View\Element\Template;

Class Logo extends Template {

    /**
     * @var \Magento\Customer\Model\Session $customerSession
     */
    protected $_customerSession;

    /**
     * @var \Magento\Customer\Api\CustomerRepositoryInterface
     */
    protected $customerRepositoryInterface;

    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $storeManager;

    /**
     * @var \Magento\Framework\View\Asset\Repository
     */
    protected $viewFileUrl;

    /**
     * @param \Magento\Framework\View\Element\Template\Context $context
     * @param \Magento\Customer\Model\Session $customerSession
     * @param \Magento\Customer\Api\CustomerRepositoryInterface $customerRepositoryInterface
     * @param \Magento\Framework\View\Asset\Repository $viewFileUrl
     * @param array $data
     */

    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Customer\Model\Session $customerSession,
        \Magento\Customer\Api\CustomerRepositoryInterface $customerRepositoryInterface,
        \Magento\Framework\View\Asset\Repository $viewFileUrl,
        array $data = []
    ) {
        parent::__construct($context, $data);
        $this->_customerSession = $customerSession;
        $this->customerRepositoryInterface = $customerRepositoryInterface;
        $this->storeManager = $context->getStoreManager();
        $this->viewFileUrl = $viewFileUrl;
    }

    /**
     * Get Customer From Session
     */
    public function getCustomer() {
        if($this->_customerSession->getCustomer()->getId()){
            $customer = $this->customerRepositoryInterface->getById($this->_customerSession->getCustomer()->getId());
        }else{
            $customer = null;
        }
        return $customer;
    }

    /**
     * Get Customer Logo Url
     */
    public function getCustomerLogoUrl() {
        if($this->getCustomer() != null){
            $customer = $this->getCustomer();
            if(!empty($customer->getCustomAttribute('customer_logo'))){
                $customerLogoUrl = $this->getUrl('routename/logo/view/', ['image' => base64_encode($customer->getCustomAttribute('customer_logo')->getValue())]);
            }else{
                $customerLogoUrl = $this->viewFileUrl->getUrl('Vendorname_Modulename::images/default-logo.png');
            }
        }else{
            $customerLogoUrl = null;
        }

        return $customerLogoUrl;
    }

}

app/code/Vendorname/Modulename/Controller/Logo/View.php

<?php

namespace Vendorname\Modulename\Controller\Logo;

use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Customer\Api\CustomerMetadataInterface;
use Magento\Framework\Exception\NotFoundException;

class View extends \Magento\Framework\App\Action\Action
{
    /**
     * @var \Magento\Framework\Controller\Result\RawFactory
     */
    protected $resultRawFactory;

    /**
     * @var \Magento\Framework\Url\DecoderInterface
     */
    protected $urlDecoder;

    /**
     * @var \Magento\Framework\App\Response\Http\FileFactory
     */
    protected $fileFactory;

    /**
     * @param \Magento\Framework\App\Action\Context $context
     * @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
     * @param \Magento\Framework\Url\DecoderInterface $urlDecoder
     * @param \Magento\Framework\App\Response\Http\FileFactory $fileFactory
     */
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\Controller\Result\RawFactory $resultRawFactory,
        \Magento\Framework\Url\DecoderInterface $urlDecoder,
        \Magento\Framework\App\Response\Http\FileFactory $fileFactory
    ) {
        $this->resultRawFactory    = $resultRawFactory;
        $this->urlDecoder  = $urlDecoder;
        $this->fileFactory = $fileFactory;
        return parent::__construct($context);
    }

    /**
     * View action
     *
     * @return \Magento\Framework\View\Result\PageFactory
     * @SuppressWarnings(PHPMD.NPathComplexity)
     */
    public function execute()
    {
        $file = null;
        $plain = false;
        if ($this->getRequest()->getParam('file')) {
            // download file
            $file = $this->urlDecoder->decode(
                $this->getRequest()->getParam('file')
            );
        } elseif ($this->getRequest()->getParam('image')) {
            // show plain image
            $file = $this->urlDecoder->decode(
                $this->getRequest()->getParam('image')
            );
            $plain = true;
        } else {
            throw new NotFoundException(__('Page not found.'));
        }

        /** @var \Magento\Framework\Filesystem $filesystem */
        $filesystem = $this->_objectManager->get('Magento\Framework\Filesystem');
        $directory = $filesystem->getDirectoryRead(DirectoryList::MEDIA);
        $fileName = CustomerMetadataInterface::ENTITY_TYPE_CUSTOMER . '/' . ltrim($file, '/');
        $path = $directory->getAbsolutePath($fileName);

        if (!$directory->isFile($fileName)
            && !$this->_objectManager->get('Magento\MediaStorage\Helper\File\Storage')->processStorageFile($path)
        ) {
            throw new NotFoundException(__('Page not found.'));
        }

        if ($plain) {
            $extension = pathinfo($path, PATHINFO_EXTENSION);
            switch (strtolower($extension)) {
                case 'gif':
                    $contentType = 'image/gif';
                    break;
                case 'jpg':
                    $contentType = 'image/jpeg';
                    break;
                case 'png':
                    $contentType = 'image/png';
                    break;
                default:
                    $contentType = 'application/octet-stream';
                    break;
            }
            $stat = $directory->stat($fileName);
            $contentLength = $stat['size'];
            $contentModify = $stat['mtime'];

            /** @var \Magento\Framework\Controller\Result\Raw $resultRaw */
            $resultRaw = $this->resultRawFactory->create();
            $resultRaw->setHttpResponseCode(200)
                ->setHeader('Pragma', 'public', true)
                ->setHeader('Content-type', $contentType, true)
                ->setHeader('Content-Length', $contentLength)
                ->setHeader('Last-Modified', date('r', $contentModify));
            $resultRaw->setContents($directory->readFile($fileName));
            return $resultRaw;
        } else {
            $name = pathinfo($path, PATHINFO_BASENAME);
            $this->fileFactory->create(
                $name,
                ['type' => 'filename', 'value' => $fileName],
                DirectoryList::MEDIA
            );
        }
    }
}

app/code/Vendorname/Modulename/view/frontend/layout/customer_account_edit.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <update handle="customer_account"/>
    <body>
        <referenceContainer name="form.additional.info">
            <block class="Vendorname\Modulename\Block\Logo" name="customer_logo" template="Vendorname_Modulename::account/logo.phtml"/>
        </referenceContainer>
    </body>
</page>

app/code/Vendorname/Modulename/view/frontend/templates/account/logo.phtml

<fieldset class="fieldset info">
    <div class="field customer_logo">
        <label for="customer_logo" class="label"><span><?php /* @escapeNotVerified */ echo __('Customer Logo') ?></span></label>
        <div class="control">
            <input type="file" name="customer_logo" id="customer_logo" title="<?php /* @escapeNotVerified */ echo __('Customer Logo') ?>" class="input-text validate-filesize validate-fileextensions-image" data-validate="{required:false}" data-role="customer_logo">
            <?php 
                $customerLogoUrl = !empty($block->getCustomerLogoUrl()) ? $block->getCustomerLogoUrl() : '';
                if(!empty($customerLogoUrl)){
            ?>
                    <div class="file-preview">
                        <a class="preview-link preview-image" target="_blank" href="<?php echo $customerLogoUrl; ?>">
                            <img tabindex="0" src="<?php echo $customerLogoUrl; ?>" alt="" height="90px" width="90px">
                        </a>
                    </div>
            <?php   
                } 
            ?>
        </div>
    </div>
</fieldset>

<script>
    require([
        'jquery',
        'jquery/ui',
        'jquery/validate',
        'mage/translate'
    ], function ($) {

    $.validator.addMethod('validate-filesize', function (v, elm) {
        var maxSize = 5 * 102400;
        if (navigator.appName == "Microsoft Internet Explorer") {
            if (elm.value) {
                var oas = new ActiveXObject("Scripting.FileSystemObject");
                var e = oas.getFile(elm.value);
                var size = e.size;
            }
        } else {
            if (elm.files[0] != undefined) {
                size = elm.files[0].size;
            }
        }
        if (size != undefined && size > maxSize) {
            return false;
        }
        return true;
    }, $.mage.__('The file size should not exceed 5MB'));


    $.validator.addMethod('validate-fileextensions-image', function (v, elm) {
        var extensions = ['jpg', 'png', 'gif', 'jpeg'];
        if (!v) {
            return true;
        }
        with (elm) {
            var ext = value.substring(value.lastIndexOf('.') + 1);
            for (i = 0; i < extensions.length; i++) {
                if (ext == extensions[i]) {
                    return true;
                }
            }
        }
        return false;
    }, $.mage.__('Disallowed file type.'));
});
</script>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.