Skip to content

Magento 2 : Admin Ajax Upload File

Here’s steps how to create custom ajax upload file in admin page

  1. create controller file


filesystem           = $filesystem;
        $this->fileUploader         = $fileUploader;
        $this->mediaDirectory = $filesystem->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA);
    
        parent::__construct($context);
    }
 
    public function execute()
    {
        echo $this->uploadFile();
    }
 
    public function uploadFile()
    {
        $pubFolder = 'imagefolder/'; //folder pub/media/imagefolder/
        $fileNameKey = 'file_name';
 
        try{
            $file = $this->getRequest()->getFiles($fileNameKey);
            $fileName = ($file && array_key_exists('name', $file)) ? $file['name'] : null;
 
            if ($file && $fileName) {
                $target = $this->mediaDirectory->getAbsolutePath($pubFolder);        
                
                $uploader = $this->fileUploader->create(['fileId' => $fileNameKey]);
                $uploader->setAllowedExtensions(['jpg', 'pdf', 'doc', 'png', 'zip']);
                $uploader->setAllowCreateFolders(true);
                $uploader->setAllowRenameFiles(true);
                $result = $uploader->save($target);

                return $uploader->getUploadedFileName();
            }
        } catch (\Exception $e) {
       
            echo $e->getMessage();
        }
 
        return false;
    }
}

2. in your custom phtml file

 







Comments are closed.