Synfony 3 + Vich上传包 - 在上传文件

时间:2017-04-12 10:49:55

标签: vichuploaderbundle

我的问题是在上传文件之前检索元数据。

我的配置文件:

vich_uploader:
    db_driver: orm
    mappings:
        media:
            uri_prefix:         /uploads/
            upload_destination: '%kernel.root_dir%/../web/uploads'
            inject_on_load:     false
            delete_on_update:   true
            delete_on_remove:   true

我有一个实体MEDIA:

<?php

    namespace AppBundle\Entity;

    use Doctrine\ORM\Mapping as ORM;
    use Symfony\Component\HttpFoundation\File\File;
    use Vich\UploaderBundle\Mapping\Annotation as Vich;

    **
     * @ORM\Entity
     * @Vich\Uploadable
     */
    class Media
    {
        /**
         * @ORM\Id
         * @ORM\Column(type="integer")
         * @ORM\GeneratedValue(strategy="AUTO")
         */
        private $id;

        /**
         *
         * @Vich\UploadableField(mapping="media", fileNameProperty="fileName",originalName="originalFileName")
         *
         * @var File
         */
         private $file;

         /**
          * @ORM\Column(type="string", length=50)
          */
         private $fileName;

         /**
          * @ORM\Column(type="string", length=255, nullable=false)
          */
         private $originalFileName;

         /**
          * @ORM\Column(type="datetime")
          */
         private $updatedAt;

         /**
          * @param File|\Symfony\Component\HttpFoundation\File\UploadedFile $file
          *
          * @return Media
          */
         public function setFile(File $file = null)
         {
             $this->file = $file;

             if ($file) {
                 $this->updatedAt = new \DateTimeImmutable();
             }

             return $this;
         }

         /**
          * @return File|null
          */
         public function getFile()
         {
             return $this->file;
         }

         /**
          * @param string $fileName
          *
          * @return Media
          */
         public function setFileName($fileName)
         {
             $this->fileName = $fileName;

             return $this;
         }

         /**
          * @return string|null
          */
         public function getFileName()
         {
             return $this->fileName;
         }

         /**
          * Get id
          *
          * @return integer
          */
         public function getId()
         {
             return $this->id;
         }

         /**
          * 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 originalFileName
          *
          * @param string $originalFileName
          *
          * @return Media
          */
         public function setOriginalFileName($originalFileName)
         {
             $this->originalFileName = $originalFileName;

             return $this;
         }

         /**
          * Get originalFileName
          *
          * @return string
          */
         public function getOriginalFileName()
         {
             return $this->originalFileName;
         }
     }

这是我的控制器:

   /**
     * Creates a new media entity.
     *
     * @Route("/new", name="media_new")
     * @Method({"GET", "POST"})
     *
     * @param Request $request
     *
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function newAction(Request $request)
    {
        $media = new Media();
        $form = $this->createForm(MediaType::class, $media);

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {

            $em = $this->getDoctrine()->getManager();

            $em->persist($media);
            $em->flush();
            return $this->redirectToRoute(
                'media_list'
            );
        }

        return $this->render(
            'media/new.html.twig',
            [
                'media' => $media,
                'form' => $form->createView(),
            ]
        );
    }

我的表格:

    <?php
    /**
     * Created by PhpStorm.
     * User: rafael
     * Date: 4/10/17
     * Time: 12:46 PM
     */

    namespace AppBundle\Form;

    use AppBundle\Entity\Media;
    use AppBundle\Entity\MediaDescriptionHelper;
    use Symfony\Bridge\Doctrine\Form\Type\EntityType;
    use Symfony\Component\Form\AbstractType;
    use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
    use Symfony\Component\Form\Extension\Core\Type\FileType;
    use Symfony\Component\Form\Extension\Core\Type\SubmitType;
    use Symfony\Component\Form\FormBuilderInterface;
    use Symfony\Component\OptionsResolver\OptionsResolver;

    class MediaType extends AbstractType
    {
        /**
         * @param FormBuilderInterface $builder
         * @param array $options
         */
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder
                ->add('file', FileType::class)
                ->add('save', SubmitType::class, [
                    'attr' => ['class' => 'btn-primary btn-block']
                ]);
        }

        /**
         * @param OptionsResolver $resolver
         */
        public function configureOptions(OptionsResolver $resolver)
        {
            $resolver->setDefaults(['data_class' => Media::class]);
        }
    }

问题在于这些值的映射:

@Vich \ UploadableField(mapping =&#34; media&#34;,fileNameProperty =&#34; fileName&#34;,originalName =&#34; originalFileName&#34;)

当我提交表单时,这些值为&#39; null&#39; :

执行&INSERT INTO媒体(file_name,original_file_name,updated_at)VALUES(?,?,?)&#39;时发生异常。与params [&#34; get_image_resultat_sans_cache2.php.jpeg&#34;,null,&#34; 2017-04-12 10:11:56&#34;]:

我对所有参数都有这些问题:

https://github.com/dustin10/VichUploaderBundle/blob/master/Resources/doc/usage.md

UploadableField注释有几个选项。它们如下:

映射:必需,要使用的bundle配置中指定的映射名称; fileNameProperty :必需,包含上传文件名称的属性; size :包含上传文件大小(以字节为单位)的属性; mimeType :包含上传文件的mime类型的属性; originalName :包含上传文件的原始名称的属性。

我不知道自己做错了什么......

提交表单后,这是我的媒体(实体):

媒体{#403▼   -id:null   -file:UploadedFile {#15▼     -test:false     -originalName:&#34; get_image_resultat_sans_cache2.php.jpeg&#34;     -mimeType:&#34; image / jpeg&#34;     -size:203751     -error:0     路径:&#34; / tmp&#34;     filename:&#34; php9xsTdF&#34;     basename:&#34; php9xsTdF&#34;     路径名:&#34; / tmp / php9xsTdF&#34;     扩展名:&#34;&#34;     realPath:&#34; / tmp / php9xsTdF&#34;     时间:2017-04-12 10:11:56     mTime:2017-04-12 10:11:56     cTime:2017-04-12 10:11:56     inode:6160452     大小:203751     烫发:0100600     拥有者:1000     组:1000     输入:&#34; file&#34;     可写的:真的     可读:真实     可执行文件:false     file:true     迪尔:假     链接:false   }   -fileName:null   -originalFileName:null

在上传文件之前设置元数据似乎是个问题...

提前多多感谢...

1 个答案:

答案 0 :(得分:2)

您使用的是哪个版本的VichUploaderBundle?

注释的文档是指dev-master,而稳定文档(1.5.3)不支持开箱即用的元数据注释。

您可以看到1.5.3版本中的Vich \ UploaderBundle \ Mapping \ Annotation \ UploadableField.php仅处理注释'mapping'和'fileNameProperty'。

在dev-master中,它处理那些和大小,mimeType和originalName。

与Vich \ UploaderBundle \ Metadata \ Driver \ AnnotationDriver相同

如果要在1.5.3版本中实现此目的,则需要创建eventListener。

以下是Vich触发的事件:https://github.com/dustin10/VichUploaderBundle/blob/1.5.3/Event/Events.php