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

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

Implementation of WireMock for better testing

Spread the love WireMock is a flexible and powerful tool

Magento 2: How to selected default option in configurable options?

Spread the love Configurable products in Magento 2 allow

How To Implement Simple JWT Authentication in Django Rest Framework

Spread the love We’ll learn how to use simple JWT

Optimizing Search: Integrating Elasticsearch in Django Applications

Spread the love What is Elasticsearch? Elasticsearch is a

How to create Customer Segments

Spread the love In Magento 2, “customer

Proxy Design Pattern and Requisition List in Magento 2

Spread the love Requisition List in Magento 2 Requisition

bluethinkinc Blogs