Working with Magento sometimes require various file uploads to store and use in the extension. While using backend, you may need uploading for example CSV, to add data and use somewhere or validate data from frontend. And from frontend, you need file upload option to let users upload screenshots, images or any other input files you need to store and further use or process.

By defualt, Magento 2 accepts all kind of input types such as text, radio button, check box etc. and allows to extend default interface to add fields without any hassle. Here, I will share the custom code to add file upload control both the backend and frontend of Magento 2.

Go to Stores > Configuration > Sales, create a new section custom_section, create a new group of fields custom_group, and create a file upload custom_file_upload with following code.

Here, Group in the code include the fields that permit you to upload the files as need. ID attribute points to the certain custom file upload and it is unique per group. And type attribute is set for the file type, if you want to allow uploading image, it should be replaced with image.
Even if you have got upload file option but it will still not work. to make them work,

  • You need to set the upload folder, check allowed extensions, validate file size and save the file path to database. Default backend model for file upload is Magento\Config\Model\Config\Backend\File. Add upload_dir – upload directory to run the file.
  • Magento 2 allows many types of files to upload but if you want to restrict some file types, to do the same go to system.xml file to be \[Vendor]\[ModuleName]\Model\Config\Backend\CustomFileType and put below code which allows only csv and xls file types. change the code as per your requirements.
just as backend, same technique can be used to add file upload control in frontend.
Take a look at sample code to add a field to a form of type file:
Implementing this code will have a form with an input type=”file” box from which you can select the file you want to upload and press “save”.
Now we will need to create a controller to handle the request in app/code/[Vendor]/[ModuleName]/Controller/[ControllerName].php
In the above code, Magento\Framework\File\Uploader model handles upload, validation and file saving.

File Uploads in System Configuration

While adding file upload control to the system configuration area of Magento, you just need to specify some configuration to give Magento a clue as to where the file should be uploaded.

That’s it. Simply by adding few lines of code both in backend and frontend, you can easily create file upload control. Let me know where you have used this code and how it helped. Even feel free to ask if you have any questions in comment section, I would be glad to help.

Magento 2 Mobile APP

Click to rate this post!
[Total: 21 Average: 3.9]