简体   繁体   中英

How to edit and remove image from post (CRUD Symfony 4)

I've started a new project, creating Entities, Controller, CRUD. I added field to upload images, when I create a new one, everything works fine but I'm struggling with edit and delete.

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

/**
 * @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');
}

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

I would like to know how to remove/edit image file from images_directory.

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

EDIT: I've found this solution:

Post_edit:

/**
 * @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');
}

CAUTION: you are storing user data as directory/file, this is dangerous and strongly discouraged, because the user can alter the POST data and overwrite/delete/read stuff from other users and your filesystem. This is a BIG security exploit. You should determine the filepath yourself, not let the user browse through your directories.

That being said, if you still want to proceed using this approach:

You are not storing the filepath, so you can never know where the file was stored. Store the filepath together with the filename in your post, like this:

//...

            // 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);
//...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM