我还在学习Symfony2。但在这里,我对我为项目创建的媒体服务有一个理解问题。
当我使用媒体控制器时,文件上传,我的媒体实体已完成文件的信息和我需要的东西。
但是当我尝试将此MediaBundle用作我设置的Handler的服务时,它不起作用。 调用ImageFormHandler,但不上传任何内容。我不明白为什么和ImageForm完全无效。
我不想使用任何SF2 Bundle来了解Symfony2,也因为它们大部分时间都比我们需要的更多。
我希望你能帮助我。 非常感谢你。
抱歉:这也是我在StackOverflow上的第一篇文章。
InfoPro的/ MediaBundle / DefaultController.php
namespace Infopro\MediaBundle\Controller;
use Infopro\MediaBundle\Form\Handler\ImageFormHandler;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
class DefaultController extends Controller
{
/**
* Upload forms
*
* @Route("/upload", name="media_upload_index")
* @Template("InfoproMediaBundle:Default:index.html.twig")
* @param \Symfony\Component\HttpFoundation\Request $request
* @return array
*/
public function indexAction(Request $request)
{
$formImage = $this->get('media.image.form');
$formPdf = $this->get('media.pdf.form');
$this->get('media.image.form.handler')->process($request);
$this->get('media.pdf.form.handler')->process($request);
return array(
'formImage' => $formImage->createView(),
'formPdf' => $formPdf->createView()
);
}
/**
* Upload forms
*
* @Route("/uploadimage/", name="media_upload_image")
* @Route("/uploadimage/{uploadedto}/{class}", name="media_upload_image_params")
* @param \Symfony\Component\HttpFoundation\Request $request
* @param string $uploadedto
* @param string $class
* @return array
*/
public function uploadImageAction(Request $request,$uploadedto = null, $class = null)
{
/** @var ImageFormHandler $mediaImageFormHandler */
$imageFormHandler = $this->get('media.image.form.handler');
$media = $imageFormHandler->process($request);
if($media !== null)
{
return new JsonResponse(['success' => true,'media' => $media, 'uploadedto' => $uploadedto, 'class' => $class]);
}
return new JsonResponse(['success' => false,'uploadedto' => $uploadedto, 'class' => $class]);
}
}
MediaBundle / Entity.php
namespace Infopro\MediaBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Gedmo\Mapping\Annotation as Gedmo;
use Uploadable\Fixture\Entity\Image;
/**
* Media
*
* @ORM\Table(name="mediatheque")
* @ORM\Entity
*/
class Media
{
static $defaultMimeType = 'image/jpeg';
static $defaultType = 0;
static $defaultHeight = 1000;
static $defaultWidth = 1000;
static $rootDir = null;
static $widthInImageSize = 0;
static $heightInImageSize = 1;
static $defaultDirectory = 'default';
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* @var string
*
* @ORM\Column(name="original_name", type="string", length=255)
*/
private $originalName;
/**
* @var string
*
* @ORM\Column(name="mime_type", type="string", length=50)
*/
private $mimeType;
/**
* @var integer
*
* @ORM\Column(name="size", type="integer")
* @Assert\Type(type="integer")
*/
private $size;
/**
* @var integer
*
* @ORM\Column(name="height", type="integer")
* @Assert\Type(type="integer")
*/
private $height;
/**
* @var integer
*
* @ORM\Column(name="width", type="integer")
* @Assert\Type(type="integer")
*/
private $width;
/**
* @var integer
*
* @ORM\Column(name="type", type="integer")
* @Assert\Type(type="integer")
*/
private $type;
/**
* @var \DateTime
*
* @ORM\Column(name="created_at", type="datetime")
* @Gedmo\Timestampable(on="create")
*/
private $createdAt;
/**
* @var \DateTime
*
* @ORM\Column(name="updated_at", type="datetime")
* @Gedmo\Timestampable(on="update")
*/
private $updatedAt;
/**
* @var string
*
* @ORM\Column(name="image", type="string", length=255, nullable=true)
*
* @Assert\Image(
* maxSize="1000000",
* maxWidth = 1000,
* maxHeight = 1000,
* mimeTypes = {
* "image/jpeg",
* "image/jpg",
* "image/gif",
* "image/png",
* }
* )
*/
private $image;
/**
* @var string
* @Assert\File(
* maxSize="300000000",
* mimeTypes = {"application/pdf"},
* )
* @ORM\Column(name="pdf", type="string", length=255,nullable=true)
*/
private $pdf;
/**
* @var string
* @ORM\Column(name="uploaded_to", type="string", length=50)
*/
private $uploadedTo;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* @param string $name
*
* @return Media
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Set originalName
*
* @param string $originalName
*
* @return Media
*/
public function setOriginalName($originalName)
{
$this->originalName = $originalName;
return $this;
}
/**
* Get originalName
*
* @return string
*/
public function getOriginalName()
{
return $this->originalName;
}
/**
* Set mimeType
*
* @param string $mimeType
*
* @return Media
*/
public function setMimeType($mimeType)
{
$this->mimeType = $mimeType;
return $this;
}
/**
* Get mimeType
*
* @return string
*/
public function getMimeType()
{
return $this->mimeType;
}
/**
* Set size
*
* @param integer $size
*
* @return Media
*/
public function setSize($size)
{
$this->size = $size;
return $this;
}
/**
* Get size
*
* @return integer
*/
public function getSize()
{
return $this->size;
}
/**
* Set height
*
* @param integer $height
*
* @return Media
*/
public function setHeight($height)
{
$this->height = $height;
return $this;
}
/**
* Get height
*
* @return integer
*/
public function getHeight()
{
return $this->height;
}
/**
* Set width
*
* @param integer $width
*
* @return Media
*/
public function setWidth($width)
{
$this->width = $width;
return $this;
}
/**
* Get width
*
* @return integer
*/
public function getWidth()
{
return $this->width;
}
/**
* Set type
*
* @param integer $type
*
* @return Media
*/
public function setType($type)
{
$this->type = $type;
return $this;
}
/**
* Get type
*
* @return integer
*/
public function getType()
{
return $this->type;
}
/**
* Set createdAt
*
* @param \DateTime $createdAt
*
* @return Media
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* @return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set updatedAt
*
* @param \DateTime $updatedAt
*
* @return Media
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* Get updatedAt
*
* @return \DateTime
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* Set image
*
* @param string $image
*
* @return Media
*/
public function setImage($image)
{
$this->image = $image;
return $this;
}
/**
* Get image
*
* @return string
*/
public function getImage()
{
return $this->image;
}
/**
* Set pdf
*
* @param string $pdf
*
* @return Media
*/
public function setPdf($pdf)
{
$this->pdf = $pdf;
return $this;
}
/**
* Get pdf
*
* @return string
*/
public function getPdf()
{
return $this->pdf;
}
public function uploadImage()
{
if($this->image !== null) {
$newName = uniqid() . $this->name . '.' . $this->image->getClientOriginalExtension();
$this->setName($newName);
$this->setMimeType($this->image->getClientMimeType());
$this->setType(self::$defaultType);
$this->setHeight(self::$defaultHeight);
$this->setWidth(self::$defaultWidth);
$this->setOriginalName($this->image->getClientOriginalName());
$this->setSize($this->image->getClientSize());
$file = $this->image->move($this->getImageUploadRootDir(), $newName);
$this->setDimension($file);
} else {
$this->setName('noimage'.uniqid());
$this->setOriginalName('noimage');
}
}
private function setDimension($file)
{
$dimension = getimagesize($file->getPathName());
$this->setHeight($dimension[1]);
$this->setWidth($dimension[0]);
}
public function uploadZip()
{
$this->pdf->move($this->getZipUploadRootDir(), uniqid().'.pdf');
}
protected function getImageUploadRootDir()
{
return self::$rootDir.'/images/'.$this->getUploadedTo();
}
protected function getZipUploadRootDir()
{
return self::$rootDir.'/zip';
}
public function setUploadRootDir($rootDir)
{
if(self::$rootDir === null)
{
self::$rootDir = $rootDir;
}
}
/**
* @param $uploadedTo
* @return Media
*/
public function setUploadedTo($uploadedTo)
{
$this->uploadedTo = $uploadedTo;
return $this;
}
/**
* @return string
*/
public function getUploadedTo()
{
return $this->uploadedTo;
}
}
InfoPro的/ MediaBundle /资源/配置/ services.yml
parameters:
media.image.form.type.class: Infopro\MediaBundle\Form\Type\ImageFormType
media.image.form.handler.class: Infopro\MediaBundle\Form\Handler\ImageFormHandler
media.pdf.form.type.class: Infopro\MediaBundle\Form\Type\PdfFormType
media.pdf.form.handler.class: Infopro\MediaBundle\Form\Handler\PdfFormHandler
media.entity.class: Infopro\MediaBundle\Entity\Media
services:
media.image.form.type:
class: %media.image.form.type.class%
arguments:
- %media.entity.class%
tags:
- { name: form.type, alias: media }
media.image.form:
factory_method: create
factory_service: form.factory
class: Symfony\Component\Form\Form
arguments:
- @media.image.form.type
media.image.form.handler:
class: %media.image.form.handler.class%
scope: request
arguments:
- @media.image.form
- @doctrine.orm.entity_manager
- @session
- @router
- %media.root.dir%
media.pdf.form.type:
class: %media.pdf.form.type.class%
arguments:
- %media.entity.class%
tags:
- { name: form.type, alias: media_zip }
media.pdf.form:
factory_method: create
factory_service: form.factory
class: Symfony\Component\Form\Form
arguments:
- @media.pdf.form.type
media.pdf.form.handler:
class: %media.pdf.form.handler.class%
scope: request
arguments:
- @media.pdf.form
- @doctrine.orm.entity_manager
- @session
- @router
- %media.root.dir%
InfoPro的/ MediaBundle /窗体/处理程序/ ImageFormHandler.php
<?php
namespace Infopro\MediaBundle\Form\Handler;
use Doctrine\ORM\EntityManager;
use Infopro\MediaBundle\Entity\Media;
use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Bundle\FrameworkBundle\Routing\Router;
class ImageFormHandler
{
const heightInImageSize = 1;
const widthInImageSize = 0;
protected $form;
protected $em;
protected $sessions;
protected $router;
protected $rootDir;
protected $dimension = [];
public function __construct(Form $form, EntityManager $em, Session $session, Router $router, $rootDir)
{
$this->form = $form;
$this->em = $em;
$this->session = $session;
$this->router = $router;
$this->rootDir = $rootDir;
}
/**
* Process image form
*
* @param Request $request
* @return Media|null|string
*/
public function process(Request $request)
{
$media = null;
$media = $this->form->getData();
if ($request->isMethod('POST')) {
$this->form->handleRequest($request);
if ($this->form->isValid()) {
/** @var Media $media */
$media = $this->form->getData();
$uploadedto = $request->get('uploadedto') === null ? 'front' : $request->get('uploadedto');
$media->setUploadedTo($uploadedto);
$media->setUploadRootDir($this->rootDir);
$media->uploadImage();
$this->em->persist($media);
$this->em->flush();
$this->session->getFlashBag()->add('info', 'Image uploaded to Media Library');
}
}
if($media !== null)
{
return $media->getName();
}
return $media;
}
public function uploadImage(Request $request)
{
$medias = [];
foreach ($request->files as $file) {
/** @var \Symfony\Component\HttpFoundation\File\UploadedFile $file */
$this->setDimension($file);
$media = new Media();
$media->setImage($file);
$media->setUploadedTo($request->get('uploadedto'));
$media->setMimeType($file->getClientMimeType());
$media->setName($this->getUnuglifyName($file));
$media->setUploadRootDir($this->rootDir);
$media->setWidth($this->getWidth());
$media->setHeight($this->getHeight());
$media->uploadImage();
$this->em->persist($media);
$this->em->flush();
array_push($medias, $media->getId());
}
return $medias;
}
/**
* @param UploadedFile $file
*/
private function setDimension(UploadedFile $file)
{
$this->dimension = getimagesize($file->getPathName());
}
private function getWidth()
{
return $this->dimension[self::widthInImageSize];
}
private function getHeight()
{
return $this->dimension[self::heightInImageSize];
}
/**
* @param UploadedFile $file
* @return string
*/
private function getUnuglifyName(UploadedFile $file)
{
return uniqid() . $file->getClientOriginalName() . '.' . $file->getClientOriginalExtension();
}
}
InfoPro的/的appbundle / DemoController.php
/**
* @Method({"GET"})
* @Route("/image", name="image_upload")
* @Template("InfoproAppBundle:Default:image.html.twig")
*/
public function imageAction()
{
$page = new Page();
$form = $this->createForm(new PageType(), $page);
$formImage = $this->get('media.image.form');
return ['form' => $form->createView(), 'formImage' => $formImage->createView()];
}
/**
* @Method({"POST"})
* @Route("/image", name="image_upload_post")
* @Template("InfoproAppBundle:Default:image.html.twig")
* @param Request $request
* @return array
*/
public function imagePostAction(Request $request)
{
$page = new Page();
$form = $this->createForm(new PageType(), $page);
$imageFormHandler = $this->get('media.image.form.handler');
$media = $imageFormHandler->process($request);
$formImage = $this->get('media.image.form');
var_dump($media);
if($media === null) {
return ['form' => $form->createView(), 'formImage' => $formImage->createView()];
}
return ['coucou' => 'test'];
}
InfoPro的/的appbundle /窗体/类型/ PageType.php
class PageType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('title', 'text', ['label' => 'Title', 'required' => true]);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(['compound' => true]);
}
public function getName()
{
return 'page';
}
}
InfoPro的/ DatabaseBundle /实体/ page.php文件
namespace Infopro\DatabaseBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Page
*
* @ORM\Table(name="pages")
* @ORM\Entity(repositoryClass="Infopro\DatabaseBundle\Entity\PageRepository")
*/
class Page
{
/**
* @var integer
*
* @ORM\Column(name="id_pages", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="label", type="string", length=45)
*/
private $title;
/**
* @var string
*
* @ORM\Column(name="image_header", type="string", length=300)
*/
private $imageHeader;
/**
* @var string
*
* @ORM\Column(name="image_header_reabo", type="string", length=300)
*/
private $imageHeaderRenew;
/**
* @var string
*
* @ORM\Column(name="url_site", type="string", length=300)
*/
private $url;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* @param string $title
*
* @return Page
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set imageHeader
*
* @param string $imageHeader
*
* @return Page
*/
public function setImageHeader($imageHeader)
{
$this->imageHeader = $imageHeader;
return $this;
}
/**
* Get imageHeader
*
* @return string
*/
public function getImageHeader()
{
return $this->imageHeader;
}
/**
* Set imageHeaderRenew
*
* @param string $imageHeaderRenew
*
* @return Page
*/
public function setImageHeaderRenew($imageHeaderRenew)
{
$this->imageHeaderRenew = $imageHeaderRenew;
return $this;
}
/**
* Get imageHeaderRenew
*
* @return string
*/
public function getImageHeaderRenew()
{
return $this->imageHeaderRenew;
}
/**
* Set url
*
* @param string $url
*
* @return Page
*/
public function setUrl($url)
{
$this->url = $url;
return $this;
}
/**
* Get url
*
* @return string
*/
public function getUrl()
{
return $this->url;
}
}