Categories
Magento 2

Magento 2 – File or image upload via frontend custom module form and Controller

Today I will discuse how to File or image upload via frontend custom module form and Controller. Open your module form.phtml file and make sure that the form attribute method to post method=”post” and also make sure that the form attribute enctype like enctype=”multipart/form-data”.

Also make sure that INPUT field type attribute type=”file”, I have use file field name “filesubmission”.

Now open you costom module Controller php file VENDOR\MODULE\Controller\Index\Post.php and use some library class for DirectoryList, UploaderFactory and Filesystem in top of file below namespace.

Now add some protected on top of Controller class before __construct() method.

Now update your Controller method public function __construct() like below.

Now add code for fileupload in your Controller method public function execute(). You can see I do not use $_FILES Global Variable in Magento because it does not meet with Magento standards. Instead of $_FILES Variable please use $this->getRequest()->getFiles();

Here filesubmission is the input name and also the field name of database table.
Upload image file will be saved at pub/media/requestaquote directory.
And $data[‘filesubmission’] = $imagePath; the value of $imagePath; that will be saved in the database field.

Thank you for carefully read my article If you have any query please Leave your query on following comment section or contact with us. Please SHARE

Related Articles

3 replies on “Magento 2 – File or image upload via frontend custom module form and Controller”

My brother suggested I would possibly like this blog.
He was once entirely right. This publish actually made my
day. You can not imagine simply how a lot time I had spent for
this information! Thank you!

Excellent blog here! Also your site loads up fast! What web host are you
using? Can I get your affiliate link to your host? I wish my web site loaded up
as fast as yours lol

Leave a Reply

Your email address will not be published. Required fields are marked *