【问题标题】:How to edit and remove image from post (CRUD Symfony 4)如何从帖子中编辑和删除图像(CRUD Symfony 4)
【发布时间】:2021-07-27 14:03:10
【问题描述】:

我开始了一个新项目,创建实体、控制器、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", name="post_edit", methods={"GET","POST"})
 */
public function edit(Request $request, 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(), 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';
            }

            
            $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', [
        'post' => $post,
        'form' => $form->createView(),
    ]);
}

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

Post_delete:

/**
 * @Route("/{id}", name="post_delete", methods={"POST"})
 */
public function delete(Request $request, Post $post, 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');
}

【问题讨论】:

  • 您的问题是什么?请更详尽地描述您的问题
  • 删除帖子时,我正在从 images_directory 中查找图像路径。当我编辑帖子时,我得到“找不到文件”。由 ConstraintViolation 引起。

标签: php symfony symfony4


【解决方案1】:

注意:您将用户数据存储为目录/文件,这是危险的,强烈建议不要这样做,因为用户可以更改 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);
//...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多