Add Image Upload  in Configuration

One of the many configuration fields you can add in Magento 2 configuration is the image file upload. This field needs a bit of extra code as a backend model and some other options have to be defined. Let's see together how we can add an Image Upload field.

Magento 2 provides us a ready image file upload field that we can easily use out of the box. It uses a default backend model which is located under vendor/magento/module-config/ModelConfig/Backend/Image.php. It accepts also the option upload_dir for defining the directory path that uploaded files will be save.

Let's start by creating a system.xml file for our module which is located under app/code/<Namespace>/<Modulename>/etc/adminhtml/.

For our example we will use the Namespace MageVisionand the Modulename Blog4. The code below adds an image file upload field using the default image backend model and image files will be saved under /pub/media/blog/post4/default/.

In case we need to modify the default image backend model, we can create a custom one extending the default. In the system.xml file we have to define that our image field will use our custom backend model. An example of defining a custom image backend model is the following one.

A complete example of our module system.xml is the following.

Afterwards we have to create the custom image backend model that we defined in the system.xml above and it will be under app/code/MageVision/Blog4/Model/Config/Backend/Image for our example. In the system.xml above the upload_dir option is missing because it will be defined in our custom image backend model. In our model we can define more things like the directory path and the upload max file size in kilobytes. We can also extend some default functionality like the allowed extensions for uploaded files, the info about the scope and define a beforesave action for saving changes and deleting file if "delete" option passed.

Let's check now in Magento admin the configuration under Stores → Configuration → MageVision Blog Posts → Post 4 and see how the upload image field look like.

Finally to complete our example as an extension we will need to define also ACL acl.xml for the configuration in our extension under app/code/MageVision/Blog4/etc/.

The full example as extension can be found hereFeel free to share this post and ask your questions in the comments below.

Till next time!