File Upload in System Configuration in Magento2

Following files and steps will help you to add file upload in system configuration with custom file type validation.

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
    <system>
        <tab id="codedecorator" class="code-config-tab"  translate="label" sortOrder="300"> 
            <label><![CDATA[Decorator Extensions]]></label> 
        </tab> 
        <section id="codedecorator_learn" translate="label" type="text" sortOrder="99" showInDefault="1" showInWebsite="1" showInStore="1">
            <label>Company Agreement</label>
            <tab>codedecorator</tab>
            <resource>Codedecorator_Learn::config</resource>
            <group id="general" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="0" showInStore="0">
                <label>General</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>
                <backend_model>Codedecorator\Learn\Model\Config\Backend\File</backend_model>
                <upload_dir config="system" scope_info="1">cdlearn</upload_dir>
            </field>
            </group>
        </section>
    </system>
</config>
<?php

namespace Codedecorator\LearnCompanyAccount\Model\Config\Backend;

class File extends \Magento\Config\Model\Config\Backend\File
{
    public function _getAllowedExtensions() {
        return ['pdf'];
       //return ['pdf','svg','jpeg'];
    }
}

We have requirement of PDF file only so we have pub/media/cdlearn/defaultkept pdf only if you have other extension to be checked or validate than just remove the comment. Uploaded file will be available in the pub/media/cdlearn/default folder

How useful was this post?

Click on a star to rate it!

Average rating / 5. Vote count:

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

Leave a Reply

Your email address will not be published.