如何编辑和删除帖子中的图像 (CRUD Symfony 4)

问题描述

我开始了一个新项目,创建实体、控制器、CRUD。 我添加了用于上传图片的字段,当我创建一个图片时,一切正常,但我在编辑和删除方面遇到了困难。

==============

/**
 * @Route("/{id}/edit",name="post_edit",methods={"GET","POST"})
 */
public function edit(Request $request,Post $post): Response
{
    $form = $this->createForm(PostType::class,$post);
    $form->handleRequest($request);
    

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

        /** @var UploadedFile $imageFile */
        $imageFile = $form->get('image')->getData();

        if ($imageFile) {
            $originalFilename = pathinfo($imageFile->getClientOriginalName(),PATHINFO_FILENAME);

            $safeFilename = transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()',$originalFilename);
            $newFilename = $safeFilename.'-'.uniqid().'.'.$imageFile->guessExtension();

            // Move the file to the directory
            try {
                $imageFile->move(
                    $this->getParameter('images_directory'),$newFilename
                );
            } catch (FileException $e) {
                echo 'Impossible d\'enregistrer l\'image';
            }

            $post->setimage($newFilename);
        }
        
        $this->getDoctrine()->getManager()->flush();

        return $this->redirectToRoute('post_index');
    }

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

/**
 * @Route("/{id}",name="post_delete",methods={"POST"})
 */
public function delete(Request $request,Post $post): Response
{
    if ($this->isCsrftokenValid('delete'.$post->getId(),$request->request->get('_token'))) {
        
        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->remove($post);
        $entityManager->flush();


    }

    return $this->redirectToRoute('post_index');
}

==============

我想知道如何从 images_directory 中删除/编辑图像文件

==============

编辑: 我找到了这个解决方案:

后编辑:

/**
 * @Route("/{id}/edit",Post $post,LoggerInterface $logger): Response
{
    $form = $this->createForm(PostType::class,$post);
    $form->handleRequest($request);

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

        /** @var UploadedFile $imageFile */
        $imageFile = $form->get('image')->getData();
        
        $imageFileName = $post->getimage();

        if ($imageFile) {
            $originalFilename = pathinfo($imageFile->getClientOriginalName(),$newFilename
                );
            } catch (FileException $e) {
                echo 'Impossible d\'enregistrer l\'image';
            }

            
            $pathToFile = $this->getParameter('images_directory').'/'.$imageFileName;
            if (file_exists($pathToFile)) {
                $logger->error("Le fichier $pathToFile existe.");
                unlink($pathToFile);
            } else {
                $logger->error("Le fichier $pathToFile n'existe pas.");
            }

            $post->setimage($newFilename);
        }

        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->persist($post);
        $entityManager->flush();

        return $this->redirectToRoute('post_index');
    }

    return $this->render('post/edit.html.twig',]);
}

==============

发布_删除

/**
 * @Route("/{id}",LoggerInterface $logger): Response
{
    if ($this->isCsrftokenValid('delete'.$post->getId(),$request->request->get('_token'))) {

        $imageFileName = $post->getimage();
        $pathToFile = $this->getParameter('images_directory').'/'.$imageFileName;
        if (file_exists($pathToFile)) {
            $logger->error("Le fichier $pathToFile existe.");
            unlink($pathToFile);
        } else {
            $logger->error("Le fichier $pathToFile n'existe pas.");
        }

        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->remove($post);
        $entityManager->flush();
    }

    return $this->redirectToRoute('post_index');
}

解决方法

注意:您将用户数据存储为目录/文件,这是危险的,强烈建议不要这样做,因为用户可以更改 POST 数据并覆盖/删除/读取其他用户和您的文件系统的内容。这是一个巨大的安全漏洞。您应该自己确定文件路径,而不是让用户浏览您的目录。

话虽如此,如果您仍想继续使用这种方法:

您没有存储文件路径,因此您永远无法知道文件的存储位置。将文件路径与文件名一起存储在您的帖子中,如下所示:

//...

            // Move the file to the directory
            try {
                $pathToFile = $this->getParameter('images_directory').'/'.newFilename;
                $imageFile->move(
                    $this->getParameter('images_directory'),$newFilename
                );
            } catch (FileException $e) {
                echo 'Impossible d\'enregistrer l\'image';
            }

            $post->setImage($pathToFile);
//...