How to upload file in Magento 2

Blog
Spread the love

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.

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

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

After create index.phtml we create upload.php controller

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

A route_name is a unique name that you must set in routes.xml file for executing the action.

bluethinkinc_blog

bluethinkinc_blog

2022-11-28

0

Leave a Reply

Your email address will not be published. Required fields are marked *

Find More Blogs

Enhancing Productivity with Dynamics 365: The Power of Session Restore

Spread the love Enhancing Productivity with Dynamics 365:

Salesforce Admin

Spread the love In our last blog, we discussed common

Unlocking AI with Spring Boot: Real-World Use Cases and Solutions

Spread the love Artificial Intelligence (AI) has moved from

Enhancing Performance with Reactive Java: A Beginner-Friendly Guide

Spread the love In today’s fast-paced software

Integrating Azure Function with Dynamics 365

Spread the love Signup on azure portal and make sure to

How to Create a Power Apps Component Framework (PCF) with React

Spread the love If youʼve been looking to supercharge your

Customize lead qualification for a seamless experience

Spread the love When the 2024 Release Wave 2 was launched,

Create a Custom Console Command in Spryker

Spread the love In Spryker, developers can create custom

SALESFORCE

Spread the love Salesforce is a cloud-based software

CRUD Operation in Spryker Backoffice with a Custom Module

Spread the love Spryker is a highly flexible and modular

bluethinkinc Blogs