Magento 2 File uploader uicomponent in frontend

A little blog on how to use the file-uploader.js uicomponent.

Case: Let’s say you want customers to be able to upload a csv with products and qty to order.

Step 1: Your phtml

In your .phtml you can use the following code snippet to initiate a ajax file uploader.

<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",
                   "allowedExtensions": "csv",
                   "uploaderConfig": {
                   		"url": "<?php echo $block->getUrl('{router}/{controller}/upload'); ?>"
                   }
               }
           }
       }
   }
}

</script>

Tip: The uploader comes with a nice #dropzone which you can style.

Checkpoint 1:  When u drag in or upload a csv file, and you monitor you ajax calls in your browser extension, you will see a files post to the configured controller.

Step 2: Your controller

	
<?php


namespace Experius\CodeBlogFrontendFileUploader\Controller\Upload;

class Ajax extends \Magento\Framework\App\Action\Action
{

    protected $resultPageFactory;
    protected $jsonHelper;

    /**
     * Constructor
     *
     * @param \Magento\Framework\App\Action\Context  $context
     * @param \Magento\Framework\Json\Helper\Data $jsonHelper
     */
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory,
        \Magento\Framework\Json\Helper\Data $jsonHelper
    ) {
        $this->resultPageFactory = $resultPageFactory;
        $this->jsonHelper = $jsonHelper;
        parent::__construct($context);
    }

    /**
     * Execute view action
     *
     * @return \Magento\Framework\Controller\ResultInterface
     */
    public function execute()
    {

    $error = false;

    // Do something with the file post var_dump($_FILES['files'])

    $result = ['error'=>$error,'success'=> ($error) ? false : true ];
        
	try {
            return $this->jsonResponse($result);
        } catch (\Magento\Framework\Exception\LocalizedException $e) {
            return $this->jsonResponse($e->getMessage());
        } catch (\Exception $e) {
            $this->logger->critical($e);
            return $this->jsonResponse($e->getMessage());
        }
    }

    /**
     * Create json response
     *
     * @return \Magento\Framework\Controller\ResultInterface
     */
    public function jsonResponse($response = '')
    {
        return $this->getResponse()->representJson(
            $this->jsonHelper->jsonEncode($response)
        );
    }
}

Checkpoint 2: The response of the ajax of the upload should be valid now.