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

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

How to create custom module on Spryker for Backoffice?

Spread the love Creating a custom module in Spryker

How to Install Spryker Project with Docker on Local Machine

Spread the love Spryker is a flexible and scalable commerce

How to Add a Custom Tab to the Customer Order Detail Page in Magento 2

Spread the love Adding a custom tab to the Order Detail

Exception Handling in Java

Spread the love Introduction – Exception:An unwanted

How to add custom less file in Magento2

Spread the love Source files *.css included into layout

Spring Boot Microservices

Spread the love Microservices architecture has become

bluethinkinc Blogs