donglu1472 2018-10-01 05:09
浏览 57
已采纳

如何在symfony中编辑上传的图像

I want to edit existing image but I could not update .Please can anyone help me.

I have used my form type in this way

$builder->add('picture', FileType::class,['label'=> 'Picture', 'required'=> false, 'data_class'=> null]);
    $builder->add('submit',SubmitType::class, ['label' => 'Submit', 'attr' => ['class'=>'contact100-form-btn']]);

I have following entity

 /**
 * @var string
 *
 * @ORM\Column(name="picture", type="string", length=255, nullable=true)
 *
 */
private $picture;

I have used my form handling in this way

$form = $this->createForm(userType::class, $userEntity, ['action'=>$actionUrl]);
    $form->handleRequest($request);
    if ($form->isSubmitted()) {
        dump($form->getData());die;}

Now when I am using this form in twig {{ form_widget(form.picture) }} the value is missing in input field <input type= "file" name= "picture"> I am not getting value of existing image on upload button.

controller for edit action

public function editUserData(Request $request, $id) {

    $userEntity = $this->get('app.manage.user_data')->getUserById($id);
    $actionUrl = $this->generateUrl('edit_user_data', ['id' => $id]);
    $form = $this->createForm(userType::class, $userEntity, ['action' => $actionUrl]);
    $form->handleRequest($request);
    if ($form->isSubmitted()) {
        dump($form->getData());die;
        $this->addOrEditUserData($userEntity, $form, $id);
        $this->addFlash("success", "Your have successfully changes data of id=" . $id);

        return $this->redirect($this->generateUrl('display_user_data'));
    }

    return $this->render('@LillyDoo/Narayan/_edit.userData.html.twig', [
        'form' => $form->createView()

    ]);
}

Please can any help me how I can update existing image.

Thanks

  • 写回答

2条回答 默认 最新

  • doushizhou4477 2018-10-01 13:10
    关注

    here is an example for updating a file for a given entity : in your example , try this :

    In your entity :

    /**
     * @ORM\Column(type="string")
     * @Assert\File(mimeTypes={ "image/jpeg" , "image/png" , "image/tiff" , "image/svg+xml"})
     */
    private $picture;
    

    Here we are storing the name of the file as string in the database while the file is upload using for example a service that allow you to manage uploading files in a specific directory.

    your entity type :

    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('picture', null , array("attr"=> array(), 'required' => false));
    }
    

    i set the second param to null because i have been specified that it will a file input in the entity annotation .

    we suppose that the files you upload are on the /web/uploads

    your controller should be seem somethign like :

    /**  
         *
         * @Route("/{id}/edit", name="your_route_name")
         * @Method({"GET", "POST"})
         */
        public function editAction(Request $request,$id)
        {
          $userEntity = $this->get('app.manage.user_data')->getUserById($id);
          $userEntity = $this->get('app.manage.user_data')->getUserById($id);
          $actionUrl = $this->generateUrl('edit_user_data', ['id' => $id]);
          $editForm= $this->createForm(userType::class, $userEntity, ['action' => 
        $actionUrl]);
    
    
          // we must transform the image string from Db  to File to respect the form types
           $oldFileName = $userEntity->getPicture();
           $oldFileNamePath = $this->get('kernel')->getRootDir().'/../web/uploads/'.$userEntity->getPicture();
           $pictureFile = new File($oldFileNamePath);
           $userEntity->setPicture($pictureFile );
    
           $editForm->handleRequest($request);
    
            if ($editForm->isSubmitted() && $editForm->isValid()) {
                /*
               *  it means that the user has been set a new picture
               *  else :
               *  we let the old picture
               */
                if($userEntity->getPicture()!=null){
                    $newLogoFile = $userEntity->getPicture();
                   $fileName = md5(uniqid()).'.'.$newLogoFile ->guessExtension();
    
                 $newLogoFile ->move($this->get('kernel')->getRootDir().'/../web/uploads/', $fileName);
                    $newFileName = $fileUploader->upload($newLogoFile);
                    $userEntity->setPicture($newFileName);
                    $fileUploader->deleteFile($oldFileNamePath);
                }
                /**
                 * setting the picturefile because the file is not set . we modify it using the old file name .
                 */
                else{
                    $userEntity->setPicture($oldFileName);
                }
                $this->getDoctrine()->getManager()->flush();
    
        }
    

    I hope that help you . if you still have problems , just comment

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集