Categories: How ToMagento 2

Steps to ADD Custom File Upload Control in Magento 2

Working with Magento sometimes require various file uploads to store and use in the extension. While using backend, you may need uploading for example CSV, to add data and use somewhere or validate data from frontend. And from frontend, you need file upload option to let users upload screenshots, images or any other input files you need to store and further use or process.

By defualt, Magento 2 accepts all kind of input types such as text, radio button, check box etc. and allows to extend default interface to add fields without any hassle. Here, I will share the custom code toĀ add file upload control both the backend and frontend of Magento 2.

Backend:
Go toĀ Stores > Configuration > Sales, create a new sectionĀ custom_section, create a new group of fieldsĀ custom_group, and create a file uploadĀ custom_file_uploadĀ with following code.

<section id="[vendor]_[modulename]_section" translate="label" type="text" sortOrder="301" showInDefault="1" showInWebsite="1" showInStore="0">
    <label>Sales</label>
    <tab>sales</tab>
    <resource>Magento_Sales::config_sales</resource> / <!-- for ACL - only administrators can access this section.-->
    <group id="custom_group" translate="label" type="text" sortOrder="6" showInDefault="1" showInWebsite="1" >
        <label>Custom group</label>
        <field id="custom_file_upload" translate="label" type="Magento\Config\Block\System\Config\Form\Field\File" sortOrder="6" showInDefault="1" showInWebsite="1" >
            <label>Upload custom file</label>
        </field>
    </group>
</section>

Here,Ā GroupĀ in the code include the fields that permit you to upload the files as need. ID attribute points to the certain custom file upload and it is unique per group. And type attribute is set for the file type, if you want to allow uploading image, it should be replaced with image.
Even if you have got upload file option but it will still not work. to make them work,

  • You need to set the upload folder, check allowed extensions, validate file size and save the file path to database. Default backend model for file upload is Magento\Config\Model\Config\Backend\File. Add upload_dir ā€“ upload directory to run the file.
<backend_model>Magento\Config\Model\Config\Backend\File</backend_model>
<upload_dir>pub/media/myupload</upload_dir>
  • Magento 2 allows many types of files to upload but if you want to restrict some file types, to do the same go to system.xml file to be \[Vendor]\[ModuleName]\Model\Config\Backend\CustomFileType and put below code which allows only csv and xls file types. change the code as per your requirements.
<?php
 
namespace [Vendor]\[ModuleName]\Model\Config\Backend;
 
class CustomFileType extends \Magento\Config\Model\Config\Backend\File
{
    /**
     * @return string[]
     */    public function getAllowedExtensions() {
        return ['csv', 'xls'];
    }
}

Frontend:
just as backend, same technique can be used to add file upload control in frontend.
Take a look at sample code to add a field to a form of type file:

<?php
 
$fieldset->addField(
    'title',
    'file',
    [
        'name' => 'file', // to add reference later in controller. 
        'label' => __('File label'),
        'required' => true
    ]
)

Implementing this code will have a form with an input type=ā€fileā€ box from which you can select the file you want to upload and press ā€œsaveā€.
Now we will need to create a controller to handle the request inĀ app/code/[Vendor]/[ModuleName]/Controller/[ControllerName].php

<?php
 
namespace [Vendor]\[ModuleName]\Controller;
 
use Magento\Backend\App\Action;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Filesystem;
use Magento\MediaStorage\Model\File\UploaderFactory;
 
class [ControllerName] extends Action
{
    protected $fileSystem;
 
    protected $uploaderFactory;
 
    protected $allowedExtensions = ['csv']; // to allow file upload types 
 
    protected $fileId = 'file'; // name of the input file box  
 
    public function __construct(
        Action\Context $context,
        Filesystem $fileSystem,
        UploaderFactory $uploaderFactory
    ) {
        $this->fileSystem = $fileSystem;
        $this->uploaderFactory = $uploaderFactory;
        parent::__construct($context);
    }
 
    public function execute()
    {
        $destinationPath = $this->getDestinationPath();
 
        try {
            $uploader = $this->uploaderFactory->create(['fileId' => $this->fileId])
                ->setAllowCreateFolders(true)
                ->setAllowedExtensions($this->allowedExtensions)
                ->addValidateCallback('validate', $this, 'validateFile');
            if (!$uploader->save($destinationPath)) {
                throw new LocalizedException(
                    __('File cannot be saved to path: $1', $destinationPath)
                );
            }
 
            // @todo
            // process the uploaded file
        } catch (\Exception $e) {
            $this->messageManager->addError(
                __($e->getMessage())
            );
        }
    }
    
    public function validateFile($filePath)
    {
        // @todo
        // your custom validation code here
    }
 
    public function getDestinationPath()
    {
        return $this->fileSystem
            ->getDirectoryWrite(DirectoryList::TMP)
            ->getAbsolutePath('/');
    }
}

In the above code,Ā Magento\Framework\File\UploaderĀ model handles upload, validation and file saving.

File Uploads in System Configuration

While adding file upload control to the system configuration area of Magento, you just need to specify some configuration to give Magento a clue as to where the file should be uploaded.

<field id="file" translate="label comment" type="file" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
    <label>File</label>
    <upload_dir config="config/path">pub/media/myupload</upload_dir>
</field>

Thatā€™s it. Simply by adding few lines of code both in backend and frontend, you can easily create file upload control. Let me know where you have used this code and how it helped. Even feel free to ask if you have any questions in comment section, I would be glad to help.

Click to rate this post!
[Total: 21 Average: 3.9]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate šŸŽ–ļø Certified Magento DeveloperšŸ‘Øā€šŸ’». He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fondā¤ļø of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.šŸ

View Comments

  • Hi, I want to upload a file on checkout payment step when place order. Can you help me for this?
    Thanks in advance.

  • Hi, I want to upload a file on checkout payment step when place order. Can you help me for this?
    Thanks in advance.

  • How can I save the file path In database.
    For example, I want to add upload feature on front-end in Current User Account Section. where he can upload PDF.

    • The Blog is written to upload image from admin. For Frontend you will need to write code in your controller file for frontend.

  • How can I save the file path In database.
    For example, I want to add upload feature on front-end in Current User Account Section. where he can upload PDF.

    • The Blog is written to upload image from admin. For Frontend you will need to write code in your controller file for frontend.

Recent Posts

Magento 2: Add Quantity Increment and Decrement on Category Page

Hello Magento Friends, In this blog, we will discuss about adding quantity increment and decrement…

20 hours ago

How to Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

4 days ago

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

6 days ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

6 days ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

7 days ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

1 week ago