不会将图像保存在数据库Symfony 4中

时间:2019-02-26 10:48:42

标签: file-upload symfony4

我正在用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;
    }
}

Listener ThumbnailUploadListener

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

services.yaml

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

1 个答案:

答案 0 :(得分:0)

您忘了映射缩略图字段

@ORM\Column(type="string")