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

Proxy Design Pattern and Requisition List in Magento 2

Spread the love Requisition List in Magento 2 Requisition

Google Ads Conversion Tracking Through Magento Platform:

Spread the love Google Ads Conversion Tracking Through

Object Pool Pattern in Magento2

Spread the love What is Object Pool Pattern in Magento 2 An

JENKINS

Spread the love JENKINS Introduction and Installation

Virtual Type and Type

Spread the love Virtual type is one of the most common

Customize the length of Input field

Spread the love Sometimes we need to change the limit the

How to Add Custom Tab on Admin Dashboard and Count Website Total Visitor in Magento 2?

Spread the love In this blog we’ll see How to Add Custom

How to Add Sign Out Tab in Customer Account in Magento 2?

Spread the love In this blog we’ll see How to Add

How to create custom tab in product detail page in magento 2?

Spread the love In this blog we’ll see how to add

Understanding and Implementing CORS & CSRF

Spread the love What is security? The world has become more

bluethinkinc Blogs