首页 > 解决方案 > 不将图像保存在数据库 Symfony 4 中

问题描述

我正在用 symfony 编写应用程序,我想在文章中添加一张图片。我无法将图像保存到数据库中。我试图从文档中举一个例子:https ://symfony.com/doc/current/controller/upload_file.html

图片上传到服务器上的目录,不保存到数据库。

$post->setThumbnail($fileName); 正确设置图像名称

实体

    /**
     * @Assert\Image(
     *      minWidth = 500,
     *      minHeight = 300,
     *      maxWidth = 1920,
     *      maxHeight = 1080,
     *      maxSize = "1M"
     * )
     */
    private $thumbnail;

/**
     * Set thumbnail.
     *
     * @param string $thumbnail
     *
     * @return Post
     */
    public function setThumbnail($thumbnail)
    {
        $this->thumbnail = $thumbnail;

        return $this;
    }

    /**
     * Get thumbnail.
     *
     * @return string
     */
    public function getThumbnail()
    {
        return $this->thumbnail;
    }

控制器中的动作

/**
     * Add and Edit page Post.
     *
     * @Route(
     *      {"pl": "/artykyl/{slug}"},
     *      name="panel_post",
     *      defaults={"slug"=NULL}
     * )
     *
     * @param Request             $request
     * @param string|null         $slug
     * @param TranslatorInterface $translator
     *
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function post(Request $request, string $slug = null, TranslatorInterface $translator, FileUploader $fileUploader)
    {
        if (null === $slug) {
            $post = new Post();
            $newPostForm = true;
        } else {
            $post = $this->getDoctrine()->getRepository('App\Entity\Post')->findOneBy(['slug' => $slug]);
        }

        $form = $this->createForm(PostType::class, $post);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            if ($post->getThumbnail()) {
                $file = $post->getThumbnail();
                $fileName = $fileUploader->upload($file);
                $post->setThumbnail($fileName);
            }
            $em = $this->getDoctrine()->getManager();
            $em->persist($post);
            $em->flush();

            $this->addFlash('success', $translator->trans('Changes have been saved'));

            return $this->redirectToRoute('panel_post', ['slug' => $post->getSlug()]);
        } elseif ($form->isSubmitted() && false === $form->isValid()) {
            $this->addFlash('danger', $translator->trans('Corrects form'));
        }

        return $this->render('backend/blog/post.html.twig', [
            'currPage' => 'posts',
            'form' => $form->createView(),
            'post' => $post,
        ]);
    }

文件上传器

class FileUploader
{
    private $targetDirectory;

    public function __construct($targetDirectory)
    {
        $this->targetDirectory = $targetDirectory;
    }

    public function upload(UploadedFile $file)
    {
        $fileName = md5(uniqid()).'.'.$file->guessExtension();

        try {
            $file->move($this->getTargetDirectory(), $fileName);
        } catch (FileException $e) {
            // ... handle exception if something happens during file upload
        }

        return $fileName;
    }

    public function getTargetDirectory()
    {
        return $this->targetDirectory;
    }
}

监听器缩略图上传监听器

class ThumbnailUploadListener
{
    private $uploader;

    public function __construct(FileUploader $uploader)
    {
        $this->uploader = $uploader;
    }

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

        $this->uploadFile($entity);
    }

    public function preUpdate(PreUpdateEventArgs $args)
    {
        $entity = $args->getEntity();

        $this->uploadFile($entity);
    }

    private function uploadFile($entity)
    {
        // upload only works for Post entities
        if (!$entity instanceof Post) {
            return;
        }

        $file = $entity->getThumbnail();

        // only upload new files
        if ($file instanceof UploadedFile) {
            $fileName = $this->uploader->upload($file);
            $entity->setThumbnail($fileName);
        } elseif ($file instanceof File) {
            // prevents the full file path being saved on updates
            // as the path is set on the postLoad listener
            $entity->setThumbnail($file->getFilename());
        }
    }

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

        if (!$entity instanceof Post) {
            return;
        }

        if ($fileName = $entity->getThumbnail()) {
            $entity->setPost(new File($this->uploader->getTargetDirectory().'/'.$fileName));
        }
    }
}

服务.yaml

App\EventListener\ThumbnailUploadListener:
    tags:
        - { name: doctrine.event_listener, event: prePersist }
        - { name: doctrine.event_listener, event: preUpdate }
        - { name: doctrine.event_listener, event: postLoad }

标签: file-uploadsymfony4

解决方案


您忘记映射缩略图字段

@ORM\Column(type="string")


推荐阅读