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条)

报告相同问题?

悬赏问题

  • ¥15 使用CInternetSession,CHttpFile读取网页文件时有些电脑上会卡住怎么办?
  • ¥15 水下机器人的半物理仿真研究
  • ¥15 微服务假死,一段时间后自动恢复,如何排查处理
  • ¥50 webrtc-streamer TCP rtsp
  • ¥15 cplex运行后参数报错是为什么
  • ¥15 之前不小心删了pycharm的文件,后面重新安装之后软件打不开了
  • ¥15 vue3获取动态宽度,刷新后动态宽度值为0
  • ¥15 升腾威讯云桌面V2.0.0摄像头问题
  • ¥15 关于Python的会计设计
  • ¥15 聚类分析 设计k-均值算法分类器,对一组二维模式向量进行分类。