Image upload in Magento 2 using a custom module?

Custom module how to upload the image from the frontend or backend?

Magento 2 Custom Module Image Upload

Magento 2 Custom Module Image Upload

For image upload, I am assuming first that you have a form ready with enctype='multipart/form-data' the image field. For this tutorial, I am using the same module which I am using in every post. So for me, the module will be Vky_Test

Now in our module open Vky/Test/view/frontend/templates/test.phtml
First of all, add enctype='multipart/form-data'in the <form> tag
Then add input for the image file to upload. So add below inside the form wherever you want.

So for me, our edited Vky/Test/view/frontend/templates/test.phtmlwill be like below

Now open the Vky/Test/Controller/Index/Save.php
You can use this same controller code to upload the image from the admin controller make sure your controller action extends \Magento\Backend\App\Action

Right now what we have in the file is

We will need to add few things in this file.
Edited Vky/Test/Controller/Index/Save.php

Here 'image' is the input name and also the field name of my database table.
The image file will be saved at pub/media/vky/test
And $data['image'] = $imagePath; the value of $imagePath will be saved in the field(image is the field name for me) of your database table.

No Comments

Post A Comment