Magento 2: UPLOAD FILES PROGRAMMATICALLY

Magento 2 Upload Files Programmatically- SBDEVBLOG

Let’s upload files from the frontend form in this post. As we often require uploaders in backend and frontend forms.

We will use the file uploader for the front end in this post. We need to use the uploader class from the module MediaStorage of the vendor to upload the file.

Magento 2: UPLOAD FILES PROGRAMMATICALLY

<?php

namespace SbDevBlog\Uploader\Services;

use Exception;
use Magento\MediaStorage\Model\File\UploaderFactory;
use Magento\Framework\Filesystem;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Exception\LocalizedException;

class FileUploaderService
{
    /**
     * @var UploaderFactory
     */
    private UploaderFactory $uploaderFactory;

    /**
     * @var Filesystem
     */
    private Filesystem $filesystem;

    /**
     * Constructor
     *
     * @param UploaderFactory $uploaderFactory
     * @param Filesystem $filesystem ,
     */
    public function __construct(
        UploaderFactory      $uploaderFactory,
        Filesystem           $filesystem
    ) {
        $this->uploaderFactory = $uploaderFactory;
        $this->filesystem = $filesystem;
    }

    /**
     * Upload Files
     *
     * @param array $files
     * @param string|null $fileId
     * @return array|bool
     * @throws LocalizedException
     */
    public function uploadFile(array $files = [], string $fileId = null): bool|array
    {
        
        $result = false;
        // fileId must be a html file field name.
        $uploaderFactory = $this->uploaderFactory->create(['fileId' => $fileId]);
        $uploaderFactory->setAllowedExtensions(["jpg", "png", "gif", "pdf"]);
        $uploaderFactory->setAllowRenameFiles(true);
        $uploaderFactory->setFilesDispersion(true);
        $mediaDirectory = $this->filesystem->getDirectoryRead(DirectoryList::MEDIA);
        $destinationPath = $mediaDirectory->getAbsolutePath('custom_direcotory');
        try {
            $result = $uploaderFactory->save($destinationPath);
            if (!$result) {
                throw new LocalizedException(
                    __('File cannot be saved to path: %1', $destinationPath)
                );
            }

        } catch (Exception $e) {
            throw new LocalizedException(__($e->getMessage().": %1", $files["name"]));
        }
        return $result;
    }
}

Uploading files using custom code is pretty straightforward. We can provide an upload facility by using the above code. Pass an uploader field name to the variable $fieldId.

The new instance of the uploader class will be created using the factory class. The setAllowedExtension function allows setting conditions to upload files with specific extensions by passing an array. We have allowed jpg, png, gif, and pdf files to be uploaded from the front end. The Uploader class will throw an exception when uploading files with other extensions.

setAllowRenameFiles will rename the file if it is true. If true, the setFilesDispersion function will create directories according to file names in the destination directory.

The FileSystem class provides file and directory read and write operations and different paths, like absolute and relative.

That’s it. Thank you for reading the post. Magento 2: Upload files from the frontend form. Please use the comment box to share your feedback.

Also, Please subscribe and share with your connections.

Click to send a custom email programmatically.

Note: Please verify the code of this blog and the relevant git repository before using it in production.
sb dev blog adobe commece Magento 2

🙂 HAPPY CODING 🙂

One thought on “Magento 2: UPLOAD FILES PROGRAMMATICALLY

Leave a Reply

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