Magento 2 Image Preview in admin form

Magento 2 UI Component form provides various options to display many form input fields. We can also create the image upload field with preview using UI Component. This article assumes you have a basic understanding about Magento 2 UI Component.

In the below example scenario i already have a custom admin form and i will highlight the relevant sections on image upload.

Rendering the Image Field

The fileUploadercomponent works internally by using jQuery file uploader.
To render the image field we need to define the field details in UI Component as shown in the below code snippet.

We need to specify the required options in the configuration like

  • formElement – Should be defined as fileUploader
  • elementTmpl – Template file for displaying the image upload field.
  • maxFileSize – Allowed File Size in the custom form
  • uploaderConfig – Ajax Controller URL which handles the upload function.

Handling the File upload in AJAX Controller

Once the image field is rendered the next step is to handle the image upload in AJAX controller. The Controller code snippet shown below will simply read the field param passed from the custom admin form and delegate the upload functionality to the model class “uploader”. Initially the uploaded image has to be stored in the temporary directory while no data is saved.

During the model data save operation, the image will be moved to permanent location

Defining the Image Paths as Constants in Model Class

By Default all the uploaded images should be placed under pub/media directory. You need to create your sub
folder with the desired name under the pub/media directory.

The below constants should be assigned with the newly created subdirectory under pub/media folder.

Model Constructor initialization with required dependencies

Passing Values using di.xml

The values for the above model class constructor arguments can also be passed via di.xml

The Getter and setter functions should be defined under the Model Class

Defining Image Upload function in Model Class

Below function is called from the AJAX controller, this will save the image in temporary directory defined.

Image upload Preview Output

So far we have covered only the basics of image preview, still there are few more steps to be implemented like saving the image file name in database, rendering the saved image from database etc.

Considering the length of blog post, i will try to cover the remaining portions in another followup tutorial.