当我有一个字符串值时,如何传递Symfony \ Component \ HttpFoundation \ File \ UploadedFile的实例?

时间:2019-04-02 10:40:34

标签: symfony events doctrine symfony4

我正在学习Doctrine中的事件,目前正在图像上传中使用 prePersist()。我在这里使用订户。

AvatarSubscriber.php

namespace App\Subscribers;

use App\Entity\Teacher;
use App\Utils\FileManager;
use Doctrine\Common\EventSubscriber;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Doctrine\Common\Persistence\Event\LifecycleEventArgs;
use Doctrine\ORM\Events;

class AvatarSubscriber implements EventSubscriber
{
    private $_fileManager;

    public function __construct(FileManager $fileManager)
    {
        $this->_fileManager = $fileManager;
    }

    public function getSubscribedEvents()
    {
        return [
            Events::prePersist,
        ];
    }

    public function prePersist(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();

        if ($entity instanceof Teacher) {

            $file = $entity->getAvatar();
            $filename = $this->_fileManager->uploadFile($file);
            $entity->setAvatar($filename);
        }
    }
}

我正在使用 FileManager.php 设置要上传图像的名称,扩展名和目录。另外,FileManager.php也用于上传图像。

FileManager.php

namespace App\Utils;

use Psr\Container\ContainerInterface;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class FileManager
{
    public function __construct(ContainerInterface $container)
    {
        $this->_container = $container;
    }

    public function uploadFile(UploadedFile $uploadedFile )
    {
        if($uploadedFile instanceof UploadedFile)
        {
            $filename = $this->generateUniqueName() . '.' . $uploadedFile->guessExtension();
            $uploadedFile->move(
                $this->getTargetDirectory(),
                $filename
            );
            return $filename;
        }
    }

    private function generateUniqueName()
    {
        return md5(uniqid());
    }

    public function getTargetDirectory()
    {
        return $this->_container->getParameter('uploads_directory');
    }
}

在prepersist()中,使用参数$ file调用FileManager.php的upload()时,会引发错误:

  

传递给App \ Utils \ FileManager :: uploadFile()的参数1必须为   Symfony \ Component \ HttpFoundation \ File \ UploadedFile的实例,字符串   给

0 个答案:

没有答案