Magento 2How To GuideFebruary 18, 2021

How to Upload File in Magento 2 Programmatically?

How to Upload File in Magento 2 Programmatically?

I don’t think there is any action more frequently performed in an ecommerce store than uploading files and product images. Every product needs multiple images and files to give users a full understanding of how it looks and functions. For example, product images from different angles, user guide, terms of use, etc.

It’s pretty simple to upload files in Magento 2. You can either use our powerful Magento 2 Product Attachments extension to upload files of any type i.e. PDF, Docs, JPG, links, videos or embed the following code within any custom module to upload file programmatically in Magento 2.


Steps to Upload File in Magento 2 Programmatically

This can be done in 2 steps.
  1. Create a field to upload input file
  2. Controller to get request and save files
Here’s the HTML code for input file field.
<input type="file" name="upload_custom_file" id="upload_custom_file" title="Upload Custom File" class="input-text" data-validate="{required:true}">
Here’s the controller class file code.
<?php
namespace VendorName\ModuleName\Controller;
 
use Magento\Framework\App\Action\Context;
use Magento\Framework\Message\ManagerInterface;
use Magento\Framework\Filesystem;
use Magento\MediaStorage\Model\File\UploaderFactory;
class YourController extends \Magento\Framework\App\Action\Action
{
 
 protected $messageManager; 
 protected $filesystem;
 protected $fileUploader;
 
 public function __construct(
 Context $context,
 ManagerInterface $messageManager,
 ...
 Filesystem $filesystem,
 UploaderFactory $fileUploader
 )
 {
 $this->messageManager = $messageManager;
 ...
 $this->filesystem = $filesystem;
 $this->fileUploader = $fileUploader;
 
 $this->mediaDirectory = $filesystem->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA);
 
 parent::__construct($context);
 }
 
 public function execute()
 {
 // your code
 
 $uploadedFile = $this->uploadFile();
 
 // your code
 }
 
 public function uploadFile()
 {
 // this folder will be created inside "pub/media" folder
 $yourFolderName = 'your-custom-folder/';
 
 // "upload_custom_file" is the HTML input file name
 $yourInputFileName = 'upload_custom_file';
 
 try{
 $file = $this->getRequest()->getFiles($yourInputFileName);
 $fileName = ($file && array_key_exists('name', $file)) ? $file['name'] : null;
 
 if ($file && $fileName) {
 $target = $this->mediaDirectory->getAbsolutePath($yourFolderName); 
 
 /** @var $uploader \Magento\MediaStorage\Model\File\Uploader */
 $uploader = $this->fileUploader->create(['fileId' => $yourInputFileName]);
 
 // set allowed file extensions
 $uploader->setAllowedExtensions(['jpg', 'pdf', 'doc', 'png', 'zip']);
 
 // allow folder creation
 $uploader->setAllowCreateFolders(true);
 
 // rename file name if already exists 
 $uploader->setAllowRenameFiles(true); 
 
 // upload file in the specified folder
 $result = $uploader->save($target);
 
 //echo '<pre>'; print_r($result); exit;
 
 if ($result['file']) {
 $this->messageManager->addSuccess(__('File has been successfully uploaded.')); 
 }
 
 return $target . $uploader->getUploadedFileName();
 }
 } catch (\Exception $e) {
 $this->messageManager->addError($e->getMessage());
 }
 
 return false;
 }
}
That’s all about uploading files in Magento 2 programmatically. This is as straightforward as it seems. However, no question is a wrong question so don’t hesitate to contact us in case you have any questions related to this article.

Other Articles You Might Be Interested In: