In this blog we’ll learn about file uploading. File uploading means a user from a client machine wants to upload files to the server. This blog explains a simple way to implement the approach to upload files in Magento 2. In Magento 2, it is very easy to get files from the client side.
First you need to create a controller.
1 2 3 4 5 6 7 8 9 10 11 |
<?php namespace Bluethink\FileUpload\Controller\Index; use Magento\Framework\App\Action\Action; use Magento\Framework\Controller\ResultFactory; class Index extends Action { public function execute() { return $this->resultFactory->create(ResultFactory::TYPE_PAGE); } } |
You need to extend \Magento\Framework\App\Action\Action when you’re implementing a frontend controller class.
Then you need to create layout file file_index_index.xml
1 2 3 4 5 6 7 8 |
<?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"> <body> <referenceContainer name="content"> <block class="Magento\Framework\View\Element\Template" name="file_upload" template="Bluethink_FileUpload::index.phtml" /> </referenceContainer> </body> </page> |
Block class: Magento\Framework\View\Element\Template
Template file: Bluethink_FileUpload::index.phtml
We need a page to upload a file. We create index.phtml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<form action="<?= $block->getUrl('*/*/upload') ?>" class="form" id="my-form" method="post" enctype="multipart/form-data" data-mage-init='{"validation":{}}'> <fieldset class="fieldset"> <div class="field image"> <label class="label" for="image"><span><?= $block->escapeHtml(__('Image')) ?></span> </label> <div class=control> <input name="image" id="image" title="<?= $block->escapeHtmlAttr(__('Image')) ?>" class="input-file" type="file" /> </div> </div> </fieldset> <div class="actions-toolbar"> <div class="primary"> <button type="submit" title="Submit" class="action submit primary"> <span>Submit</span> </button> </div> </div> </form> |
After create index.phtml we create upload.php controller
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
<?php namespace Bluethink\FileUpload\Controller\Index; use Magento\Framework\App\Action\Action; use Magento\Framework\App\Action\Context; use Magento\Framework\App\Filesystem\DirectoryList; use Magento\Framework\Filesystem; use Magento\MediaStorage\Model\File\UploaderFactory; class Upload extends Action { public function __construct( Context $context, Filesystem $filesystem, UploaderFactory $uploaderFactory ) { $this->filesystem = $filesystem; $this->uploaderFactory = $uploaderFactory; parent::__construct($context); } public function execute() { $data = $this->getRequest()->getParams(); // returns form key as an array if ($data) { $files = $this->getRequest()->getFiles(); //returns an array containing some info of selected file like name, size, type, tmp_name if (isset($files['image']) && !empty($files['image']["name"])){ $uploaderFactory = $this->uploaderFactory->create(['fileId' => 'image']); $uploaderFactory->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']); $uploaderFactory->setAllowRenameFiles(true); $uploaderFactory->setFilesDispersion(true); $mediaDirectory = $this->filesystem->getDirectoryRead(DirectoryList::MEDIA); $destinationPath = $mediaDirectory->getAbsolutePath('Bluethink_FileUpload'); $result = $uploaderFactory->save($destinationPath); if ($result) { echo 'Image saved in pub/media/Bluethink_FileUpload directory'; } else { $resultRedirect = $this->resultRedirectFactory->create(); $resultRedirect->setPath('*/*/index'); return $resultRedirect; } } } } } |
SetAllowedExtensions : Some time we need to allow only specific file like png, jpeg, pdf. This function helps to upload given file types only.
ResultRedirectFactory: To redirect to another page.
SetAllowRenameFiles: When we upload the same file two times this function renames your file name with _ 1..
$uploaderFactory->setFilesDispersion(true); : If you set it, true code will create sub folders with the image name’s first two letters and then store the image there.
$this->filesystem->getDirectoryRead(DirectoryList::MEDIA); It is used to given path of pub/media.
$mediaDirectory->getAbsolutePath(‘Bluethink_FileUpload’); It is used to give the directory name where file is saved. Final path of directory is pub/media/Bluethink_FileUpload
Now we create routes.xml file
1 2 3 4 5 6 7 8 |
<?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 frontName="file" id="file"> <module name="Bluethink_FileUpload"/> </route> </router> </config> |
A route_name is a unique name that you must set in routes.xml file for executing the action.
bluethinkinc_blog
2022-11-28