Cyril F
Cyril F

Reputation: 1339

get image asset from postLoad doctrine event

I created an Entity Listener to upload pictures.

Entity Listener

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

Picture Manager

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

I use the postLoad to get the absolute path of my pic and just call:

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

to display it.

The generating src is

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

and Symfony seems to not like absolute path because it does not work. 404 error. The upload file is in the right place.

Upvotes: 0

Views: 132

Answers (1)

Gopal Joshi
Gopal Joshi

Reputation: 2358

Please try asset() in twig. It will target web folder of your application.

Syntax: {{ asset('<File Name>') }}

Replace:

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

With

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

I have used it in symfony 2.3. Hope it will solve your issue

Upvotes: 1

Related Questions