File upload in Magento 2 store configuration

<section id="custom_section" translate="label" type="text" sortOrder="301" showInDefault="1" showInWebsite="1" showInStore="0">
    <group id="custom_group" translate="label" type="text" sortOrder="6" showInDefault="1" showInWebsite="1" >
        <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>
            <upload_dir config="system" scope_info="1">test</upload_dir>

This gives below upload option in Magento admin custom module configuration and the file is also getting uploaded at specified path.

enter image description here

  • Just like we import tablerates.csv which also inserts data into shipping_tablerate, how do I make sure that the file content also gets inserted into custom table?
  • Did you get any solution for this? – Pribhav Dec 17 '18 at 9:58

I got solution for this. So sharing here:

You have to extend backend model file in your custom module like below:

  1. In system.xml, update code as below for input type="file"
 <field id="customfile" translate="label" type="Magento\Config\Block\System\Config\Form\Field\File" sortOrder="1" showInDefault="1" showInWebsite="0" showInStore="0">
                    <label>Custom file</label>
  1. In your custom module, Create file CustomFileType.php at below place:


  1. Override beforeSave method in that file as below:

namespace Vendor\Package\Model\Config\Backend;

class CustomFileType extends \Magento\Config\Model\Config\Backend\File

    public function beforeSave()
        $value = $this->getValue();
        $file = $this->getFileData();
        if (!empty($file)) {

            /*** Here you can write your custom code to save data in custom table ***/

            $uploadDir = $this->_getUploadDir();
            try {
                /** @var Uploader $uploader */
                $uploader = $this->_uploaderFactory->create(['fileId' => $file]);
                $uploader->addValidateCallback('size', $this, 'validateMaxSize');
                $result = $uploader->save($uploadDir);
            } catch (\Exception $e) {
                throw new \Magento\Framework\Exception\LocalizedException(__('%1', $e->getMessage()));

            $filename = $result['file'];
            if ($filename) {
                if ($this->_addWhetherScopeInfo()) {
                    $filename = $this->_prependScopeInfo($filename);
        } else {
            if (is_array($value) && !empty($value['delete'])) {
            } elseif (is_array($value) && !empty($value['value'])) {
            } else {

        return $this;


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.