Your IP : 216.73.217.13


Current Path : /var/www/www.indacotrentino.com/www/app/code/Ashsmith/Blog/Model/
Upload File :
Current File : //var/www/www.indacotrentino.com/www/app/code/Ashsmith/Blog/Model/ImageUploader.php

<?php
namespace Ashsmith\Blog\Model;

use Magento\Framework\Filesystem;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Image\AdapterFactory;
use Magento\Framework\Filesystem\Io\File;

class ImageUploader
{
    protected $fileSystem;
    protected $directoryList;
    protected $imageAdapterFactory;
    protected $fileIo;

    /**
     * @param Filesystem $fileSystem
     * @param DirectoryList $directoryList
     * @param AdapterFactory $imageAdapterFactory
     * @param File $fileIo
     */
    public function __construct(
        Filesystem $fileSystem,
        DirectoryList $directoryList,
        AdapterFactory $imageAdapterFactory,
        \Magento\Framework\Filesystem\Driver\File $fileIo
    ) {
        $this->fileSystem = $fileSystem;
        $this->directoryList = $directoryList;
        $this->imageAdapterFactory = $imageAdapterFactory;
        $this->fileIo = $fileIo;
    }

    /**
     * Uploads image to the media folder
     *
     * @param string $imageName
     * @return string
     * @throws LocalizedException
     */
    public function saveImage($imageName)
    {
        try {
            $mediaDirectory = $this->fileSystem->getDirectoryRead(DirectoryList::MEDIA);
            $uploadDir = 'entity/images';
            $uploadPath = $mediaDirectory->getAbsolutePath($uploadDir);
            if (!$this->fileIo->isDirectory($uploadPath)) {
                $this->fileIo->createDirectory($uploadPath, 0777);
            }

            $filePath = $uploadPath . '/' . $imageName;
            if (move_uploaded_file($imageName, $filePath)) {
                return $uploadDir . '/' . basename($filePath);
            }

            throw new LocalizedException(__('Image upload failed.'));
        } catch (\Exception $e) {
            throw new LocalizedException(__('Error uploading image: ' . $e->getMessage()));
        }
    }
}