How to upload the csv file and read import into the database magento 2?


* XXXX_ProductImport extension
* @category 
* @package XXXX_ProductImport
* @copyright Copyright (c) 2018
* @license Open Software License (OSL 3.0)
namespace \ProductImport\Controller\Adminhtml\Imports;

ini_set('display_errors', 1);

use Magento\Framework\Controller\ResultFactory; 

use Magento\Backend\App\Action;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Filesystem;
use Magento\MediaStorage\Model\File\UploaderFactory;

class Save extends \Magento\Backend\App\Action  
    protected $fileSystem;

    protected $uploaderFactory;

    protected $allowedExtensions = ['csv']; // to allow file upload types 

    protected $fileId = 'file'; // name of the input file box  

    public function __construct(
       \Magento\Backend\App\Action\Context $context,
        Filesystem $fileSystem,
        UploaderFactory $uploaderFactory
    ) {

        $this->fileSystem = $fileSystem;
        $this->uploaderFactory = $uploaderFactory;

    public function execute()

        $destinationPath = $this->getDestinationPath();

       $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
        try {
            $uploader = $this->uploaderFactory->create(['fileId' => $this->fileId])
                ->addValidateCallback('validate', $this, 'validateFile');

            if (!$uploader->save($destinationPath)) {
                throw new LocalizedException(
                    __('File cannot be saved to path: $1', $destinationPath)
                return $resultRedirect;

            // @todo
            // process the uploaded file
        } catch (\Exception $e) {

            return $resultRedirect;

    public function validateFile($filePath)

        echo "hi";

        // @todo
        // your custom validation code here

    public function getDestinationPath()
        return $this->fileSystem

Here is the easy way to upload file and import/export data by CSV in Magento 2


To know about CSV files go here:


Happy Learning.

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.