0

I want to provide a provision for uploading an image the image, should move/save to the custom folder which I have created in pub/media please be specific while explaining the code it will help me a lot thank you!

4
  • Follow this one : rohanhapani.com/… Jan 20 at 6:39
  • @RohanHapani I want to create using a normal PHP input field, not through the UI component can you please guide me on this thank you! Jan 20 at 6:44
  • Please describe more
    – Msquare
    Jan 20 at 7:01
  • @Msquare when I upload an image it should send an ajax call and in that, I want to send a response and save the image in pub media through which I can access the image. Jan 20 at 7:32

1 Answer 1

0

Try below solution:

Add file upload input in your phtml

<li class="field upload front_img required full-width">
          <div class="item">
            <div class="image_upload front" id="image_upload_front" style="background-size: contain;">
                <input type="file" name="front_img" id="front_img" data-size="13" data-validate="{required:true}">
            </div>
            <div id="attachmentFilesFrontImg" class="attachmentfiles"></div>
          </div>
          <h3>Front*</h3>
        </li>

Send Ajax Request from phtml file:

/**** Upload Image ****/
    $("#front_img").change(function(){
        var data = $("#onlinequote-form").get(0);
        jQuery.ajax({
            url: "<?php echo $this->getUrl(); ?>controllername/index/addFrontImgCustomize?isAjax=true' ?>",
            type: "POST",
            data: new FormData(data),
            processData: false,
            contentType: false,
            showLoader: true,
            success: function (response) {
              if(response.error == false)
              {
                $('div.actions').show();
                $("#attachmentFilesFrontImg").html(response.data.html);
                $('#front_img').attr("src", response.data.path);
              }
            },
        });
    });

Create Ajax controller AddFrontImgCustomize.php at vendor\module\Controller\Index.

<?php
    namespace vendor\module\Controller\Index;

    use Magento\Framework\Json\Helper\Data as JsonHelper;

    class AddFrontImgCustomize extends \Magento\Framework\App\Action\Action
    {
        protected $_pageFactory;
        protected $connection;
        protected $_mediaDirectory;
        protected $_fileUploaderFactory;
        public $_storeManager;

        public function __construct(
            \Magento\Framework\App\Action\Context $context,
            \Magento\Framework\App\ResourceConnection $connection,
            JsonHelper $jsonHelper,
            \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
            \Magento\Framework\Filesystem $filesystem,
            \Magento\MediaStorage\Model\File\UploaderFactory $fileUploaderFactory,
            \Magento\Store\Model\StoreManagerInterface $storeManager,
            \Magento\Framework\View\Result\PageFactory $pageFactory)
        {
            $this->_pageFactory = $pageFactory;
            $this->connection = $connection;
            $this->jsonHelper = $jsonHelper;
            $this->resultJsonFactory = $resultJsonFactory;
            $this->_mediaDirectory = $filesystem->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA);
            $this->_fileUploaderFactory = $fileUploaderFactory;
            $this->_storeManager = $storeManager;
            return parent::__construct($context);
        }

        public function execute(){
            $_postData = $this->getRequest()->getPost();
            $message = "";
            $newFileName = "";
            $error = false;
            $data = array();
            if (isset($_FILES['front_img']['name']) && $_FILES['front_img']['name'] != '') {
                try{
                    $target = $this->_mediaDirectory->getAbsolutePath('vendor/module');
                    //attachment is the input file name posted from your form
                    $uploader = $this->_fileUploaderFactory->create(['fileId' => 'front_img']);
                    $_fileType = $uploader->getFileExtension();
                    $uniqid = uniqid();
                    $newFileName = $uniqid .'.'. $_fileType;
                    /** Allowed extension types */
                    //$uploader->setAllowedExtensions(['jpg', 'jpeg', 'png']);
                    /** rename file name if already exists */
                    $uploader->setAllowRenameFiles(true);
                    $result = $uploader->save($target, $newFileName); //Use this if you want to change your file name
                    if ($result['file']) {
                        $_mediaUrl = $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
                        $_src = $_mediaUrl.'vendor/module/'.$newFileName;
                        $error = false;
                        $message = __("File has been successfully uploaded");
                        $html = '<div class="image item base-image" data-role="image" id="'. $uniqid .'">
                                    <div class="wallpaper-image-wrapper">
                                        <input type="hidden" value="vendor/module/'.$newFileName.'" name="frnt_img">
                                    </div>
                                </div>';
                        $data = array('filename' => $newFileName, 'path' => $_mediaUrl.'vendor/module/'.$newFileName, 'fileType' => $_fileType, 'html' => $html);
                    }
                } catch (\Exception $e) {
                    $error = true;
                    $message = $e->getMessage();
                }
            }

            $resultJson = $this->resultJsonFactory->create();
            return $resultJson->setData([
                        'message' => $message,
                        'data' => $data,
                        'error' => $error
            ]);
        }
    }

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.