【问题标题】:get image asset from postLoad doctrine event从 postLoad 学说事件中获取图像资产
【发布时间】:2016-11-08 19:49:09
【问题描述】:

我创建了一个实体监听器来上传图片。

实体监听器

<?php
namespace AppBundle\Listener;

use ...

class PictureListener
{
    private $manager;

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

    public function prePersist(PictureInterface $entity, LifecycleEventArgs $event)
    {
        $this->uploadFile($entity);
    }

    public function preUpdate(PictureInterface $entity, LifecycleEventArgs $event)
    {
        $this->uploadFile($entity);
    }

    public function postLoad(PictureInterface $entity, LifecycleEventArgs $event)
    {
        $fileName = $entity->getPicture();

        if($fileName == NULL) {
            return;
        }


        $file = new File($this->manager->getUploadDir().'/'.$fileName);
            $entity->setPicture($file);
    }

    private function uploadFile($entity)
    {
        $file = $entity->getPicture();

        if (!$file instanceof UploadedFile) {
            return;
        }

        $fileName = $this->manager->upload($file);
        $entity->setPicture($fileName);
    }
}

图片管理器

<?php

namespace AppBundle\Utils;

use Symfony\Component\HttpFoundation\File\UploadedFile;

class PictureManager
{
    private $uploadDir;

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

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

        return $fileName;
    }

    public function getUploadDir()
    {
        return $this->uploadDir;
    }
}

我使用 postLoad 来获取我的图片的绝对路径,然后调用:

<img class="img-thumbnail" src="{{ category.picture }}" alt="{{ category.name }}">

显示它。

生成的src是

/Users/*******/Projects/*******/app/../web/uploads/pictures/8fcdaf996f1a30c5b64423ebc1284391.jpeg

而且 Symfony 似乎不喜欢绝对路径,因为它不起作用。 404 错误。上传文件在正确的位置。

【问题讨论】:

    标签: doctrine-orm symfony


    【解决方案1】:

    请在 twig 中尝试asset()。它将针对您的应用程序的web 文件夹。

    语法: {{ asset('&lt;File Name&gt;') }}

    替换:

    <img class="img-thumbnail" src="{{ category.picture }}" alt="{{ category.name }}">
    

    <img class="img-thumbnail" src="{{ asset('uploads/pictures/'~category.picture) }}" alt="{{ category.name }}">
    

    我在 symfony 2.3 中使用过它。希望能解决你的问题

    【讨论】:

    • 为什么在category.picture之前使用~?你能解释一下吗?
    • 它将所有操作数转换为字符串并将它们连接起来
    • 这样我就不需要 postLoad 事件了。我知道我可以那样做。
    猜你喜欢
    • 2019-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-10
    • 1970-01-01
    • 1970-01-01
    • 2023-01-08
    相关资源
    最近更新 更多