Upload image in Magento 2 programmatically

Upload image in Magento 2 programmatically – In this article, we’re going to tell you how to upload image in Magento 2 using a form. We have a post about this feature in Magento 1, you can take a look here.

What we need to do:

  • a form with a file input.
  • a controller to get request and save the images.
  • Assuming that we save all images in “/media” directory.

1. Create a form with content:

That’s just a simple form with a file input. You can add some elements as labels if you want.

2. Create controller and upload action

Create controller file:

/app/code/VendorName/ModuleName/Controller/Index/Upload.php with content

In this file, please note:

  • ‘test_image’ is the name of form input.
  • protected property $_objectManager is already declared in class \Magento\Framework\App\Action\Action
  • we only need to declare one more property $_fileSystem which is an instance of \Magento\Framework\Filesystem
  • $result  will be an array.

So we can use that form to upload image in Magento 2. After uploading the image, you will get it in ‘pub/media’ directory. Make sure that folder is writable.

2 thoughts on “Upload image in Magento 2 programmatically

    1. Hi Chandresh,
      To upload multiple files, you can add ‘multiple’ attribute to input element

      input type=”file” name=”test_image[]” multiple=””

      And use a foreach loop in your controller to handle them one by one

      foreach( $_FILES … ){
      }

Leave a Reply

Your email address will not be published.