我创建了一个实体监听器来上传图片。
实体监听器
<?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是
/用户/ ******* /项目/ ******* /应用/../网/上传/图片/ 8fcdaf996f1a30c5b64423ebc1284391.jpeg
和Symfony似乎不喜欢绝对路径,因为它不起作用。 404错误。上传文件位于正确的位置。
答案 0 :(得分:1)
请在树枝上试试asset()
。它将定位到您应用程序的web
文件夹。
语法:
{{ asset('<File Name>') }}
替换:
<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中使用过它。希望它能解决你的问题