【问题标题】:Edit file name in entity with Symfony使用 Symfony 编辑实体中的文件名
【发布时间】:2018-09-05 11:53:45
【问题描述】:

你好(对不起,我的英语不太自信)

我实际上正在开发一个显示眼镜信息的 Symfony 网站。 现在,我需要在创建其中一个时添加一个图像。在 this 教程的帮助下,我设法做到了。

它基本上是这样工作的:我将图像上传到站点目录,然后将文件名发送到实体(存储在 MySQL 数据库中)。然后我可以在眼镜的细节中显示图像。

当我想编辑景观时出现问题。我无法更新图像的名称。我只有两种可能:1/不编辑实体,或 2/更改图像名称,然后随机获取一个我无法再显示的图像 (这些名称通常类似于 /tmp/ phpWb8kwV)

我的图像在实体 (在 Spectacle.php 中) 中是这样实例化的:

/**
* @var string
*
* @ORM\Column(name="image", type="string", length=255)
* @Assert\NotBlank(message="Veuillez ajouter une image à votre spectacle.")
* @Assert\File(mimeTypes={ "image/png" })
*/
private $image;

眼镜形式的FormType是这样(在SpectacleType.php中)

 public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('nom')
            ->add('lieu')
            ->add('dateSpectacle', null, array(
                'label' => 'Date du spectacle',
            ))
            ->add('annee')
            ->add('image',FileType::class, array(
                'label' => 'Image du spectacle',
                'required' => false, //(Still need to provide a file to finalize the creation/edit)
            ));
}

访问此页面的控制器是这样制作的(在 SpectacleController.php 中)

/**
 * Creates a new spectacle entity.
 *
 * @Route("/new", name="admin_spectacle_new")
 * @Method({"GET", "POST"})
 */
public function newAction(Request $request)
{
    $spectacle = new Spectacle();
    $form = $this->createForm('FabopBundle\Form\SpectacleType', $spectacle);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $em = $this->getDoctrine()->getManager();
//--------------------------------------------------------------------
        $file = $spectacle->getImage();            
        $fileName = (md5(uniqid())).'.'.$file->guessExtension();            
        // moves the file to the directory where image are stored
        $file->move(
            $this->getParameter('img_directory'), //(Define in the service.yml)
            $fileName
        );
        $spectacle->setImage($fileName); //(Don't know how to handle file names without this line)
//---------------------------------------------------------------------
        $em->persist($spectacle);
        $em->flush();
        return $this->redirectToRoute('admin_spectacle_show', array('id' => $spectacle->getId()));
    }

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

路由到编辑视图的功能大致相同,但我不能使用

$spectacle->setImage($fileName);

解决这个问题有两种可能性:我希望能够更新实体中的新文件名(使用其他信息)或能够在不更改文件名的情况下更新实体。

我希望我能清楚地解释我的问题... 提前感谢您的回复。

【问题讨论】:

    标签: php symfony upload doctrine symfony-3.4


    【解决方案1】:

    解决方案很愚蠢......

    事实上,访问 edit 路由的控制器没有这些行:

    $em = $this->getDoctrine()->getManager();
    ...
    $em->persist($spectacle);
    $em->flush();
    

    我需要尽快完成。如果以后有更多时间,我会尝试使用 ComurImageBundle。

    感谢您的帮助,下次我会更加小心......

    【讨论】:

      【解决方案2】:

      我在尝试上传 PDF/TEXT.. 文件时遇到了这个问题。 但是对于管理图像,我建议您使用 ComurImageBundle,它对您有很大帮助,您的问题将得到解决。 这很简单,您可以按照link 中的说明下载捆绑包。 然后你像这样修改你的代码: 1/ 在 Spectacle.php 中实例化您的图像(您的图像存储在数据库中,如字符串)

       /**
       * @ORM\Column(type="string", nullable=true)
       */
      private $image;
      

      2/ 更新你的基础(php bin/console dictionary:schema:update --force)

      3/ 在更新您的数据库架构后将这些函数添加到您的 Spectacle.php,这些函数可以让您在特定目录(web/uploads/spectacles)下上传和存储您的图像,不要忘记添加这两个库

      使用 Symfony\Component\HttpFoundation\File\UploadedFile;

      使用 Symfony\Component\Validator\Constraints 作为 Assert;

        /**
       * @Assert\File()
       */
      private $file;
      
      /**
       * Sets file.
       *
       * @param UploadedFile $file
       */
      public function setFile(UploadedFile $file = null)
      {
          $this->file = $file;
      }
      
      /**
       * Get file.
       *
       * @return UploadedFile
       */
      public function getFile()
      {
          return $this->file;
      }
      
      /**
       * @ORM\PrePersist
       */
      public function preUpload()
      {
          if (null !== $this->file) {
              $this->image = uniqid() . '.' . $this->file->guessExtension();
          }
      }
      
      /**
       * @ORM\PostPersist
       */
      public function upload()
      {
          if (null === $this->file) {
              return;
          }
      
          // If there is an error when moving the file, an exception will
          // be automatically thrown by move(). This will properly prevent
          // the entity from being persisted to the database on error
          $this->file->move($this->getUploadRootDir(), $this->image);
      }
      
      public function getUploadDir()
      {
          return 'uploads/spectacles';
      }
      
      public function getBaseUrl()
      {
          $currentPath = $_SERVER['PHP_SELF'];
      
          $pathInfo = pathinfo($currentPath);
      
          return substr($pathInfo['dirname']."/", 1);
      }
      
      public function getUploadRootDir()
      {
          return $this->getBaseUrl() . $this->getUploadDir();
      }
      
      public function getWebPath()
      {
          return null === $this->image ? null : $this->getUploadDir() . '/' . $this->image;
      }
      
      public function getAbsolutePath()
      {
          return null === $this->image ? null : $this->getUploadRootDir() . '/' . $this->image;
      }
      

      4/这样修改FormType(SpectacleType.php)

      use Comur\ImageBundle\Form\Type\CroppableImageType;
      
        public function buildForm(FormBuilderInterface $builder, array $options)
      {
          $builder->add('nom')
                  ->add('lieu')
                  ->add('dateSpectacle', null, array(
                      'label' => 'Date du spectacle',
                  ))
                  ->add('annee')
                  ->add('image', CroppableImageType::class, array('label' => 'Image', 'required' => true,
                  'uploadConfig' => array(
                      'uploadUrl' => $myEntity->getUploadDir(),       // required - see explanation below (you can also put just a dir path)
                      'webDir' => $myEntity->getUploadRootDir(),              // required - see explanation below (you can also put just a dir path)
                      'fileExt' => '*.png',  // required - see explanation below (you can also put just a dir path)
                      'showLibrary' => false,
                  ),
                  'cropConfig' => array(
                      'minWidth' => 128,
                      'minHeight' => 128,
                      'aspectRatio' => true,
                  )
              ));    
      }
      

      5/从您的控制器中删除所有这些行,您将不需要它们

      //--------------------------------------------------------------------
              $file = $spectacle->getImage();            
              $fileName = (md5(uniqid())).'.'.$file->guessExtension();            
              // moves the file to the directory where image are stored
              $file->move(
                  $this->getParameter('img_directory'), //(Define in the service.yml)
                  $fileName
              );
              $spectacle->setImage($fileName); //(Don't know how to handle file names without this line)
      //---------------------------------------------------------------------
      

      6/ 就是这样你可以在new.html.twig和edit.html.twig中调用你的图片的形式,一切都会好起来的,请尝试一下,如果有的话通知我问题。

      【讨论】:

      • 非常感谢。我马上试试。完成后我会添加评论。
      • 最后。 24 小时后,我设法导入和配置了所有内容。自图像插槽和“选择文件”按钮或显示以来,它似乎正在工作。但我得到了错误:$('#image_upload_file').fileupload is not a function 你知道它是从哪里来的吗?
      • 我认为问题来自 JS 调用,请在此处查看我的答案stackoverflow.com/a/49536246/4815698
      猜你喜欢
      • 2014-06-08
      • 1970-01-01
      • 2012-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多