How to Upload File in Magento 2 Programmatically?

How to Upload File in Magento 2 Programmatically?

If you are running an eCommerce store, then you’ll know that one of the most frequently performed actions is uploading files and product images. Indeed, you must upload multiple images and files to give users a detailed understanding about the product.

For instance, look at the below image.

guru-app

Source: GuruApp.com

As you can see on the left, the product has multiple images. Each image conveys different but essential information about the product. Therefore, we can conclude that success if eCommerce is dependent upon the quality and depth of images accompanying each product.

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.

About the Extension

Check Out: Get Magento 2 Product Attachments extension

Why you should consider using this extension compared to upload file in Magento 2 programmatically. Firstly, the extension is easy-to-use, offering a highly interactive and user-friendly interface. Even if you are not an expert in Magento development, you can use the extension to upload pdfs, images, and other essential product information.

The extension also allows you to see the uploaded files in grid view.

Magento-2-Product-Attachments

Source: FMEExtensions

It makes it easier to view attached files and saves time as you do not need to view each file separately. One of the highlights about this extension is that you can restrict the files by customer group. For instance, if you wish to show the files to select customers or those that are logged in, you can do it easily as seen below.

new-attachments

Source: FMEExtensions

This can be a great way to encourage users to sign up and buy frequently. If you are facing tough competition and wish to enhance the store’s competitiveness, this strategy can prove highly helpful. Create curiosity among the target market by providing them with selective information only.

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;
 }
}

Conclusion

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 regarding this article or anything Magento-related.

Other Articles You Might Be Interested In:

This blog was created with FME's SEO-friendly blog