从 Symfony 3 中的文件夹中删除文件

Delete files from a folder in Symfony 3

我有一个带有 createActioneditActiondeleteAction 的控制器。

我可以添加图片并从数据库中删除它们。

当我按照 Symfony 文档创建上传文件时,我也在 config.yml 这条路线中创建了

parameters:
   uploaded_restaurants: "%kernel.root_dir%/../web/uploads/restaurants"

这是我上传文件的路径。

我的问题

当我使用删除操作删除我的照片时,它会在我的数据库中删除它。但不在我的文件夹中 /web/uploads/restaurants 我也试图找到一种方法来删除我的文件夹中的它们,但无法成功。

我也试过用Filesystem()删除它们,但我一定是写得不好。

这是我的控制器:

    class MediaController extends Controller
{
    /**
     * @param Request $request
     * @param Restaurant $restaurant
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function newAction(Request $request, Restaurant $restaurant)
    {
        $media = new Media();
        $form = $this->createForm(MediaType\CreateType::class, $media);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $mediaList = $this->getDoctrine()->getRepository('AppBundle:Media')->findImageByRestaurantType($restaurant, $form->get('context')->getData());

            if ($mediaList == null || count($mediaList) < 1) {
                $media->setType('img')
                    ->setContext($form->get('context')->getData())
                    ;
            } else {
                $media = $mediaList;
            }

            $imageFile = $request->files->get('create')['name'];
            $targetDir = $this->getParameter('uploaded_restaurants');
            $imageName = $this->get('app.uploader')->upload($imageFile, $targetDir);

            /** @var  $originalName */
            $originalName = $imageFile->getClientOriginalName();
            $media->setName($imageName)
                ->setOriginalName($originalName)
                ->setCreatedAt(new \DateTime());

            $em = $this->getDoctrine()->getManager();
            $media->setRestaurant($restaurant);
            $em->persist($media);
            $em->flush();

            return $this->redirectToRoute('admin_restaurant_show_fr', array('id' => $restaurant->getId()));
        }
        return $this->render('admin/restaurant/media/new.html.twig', array(
            'restaurant' => $restaurant,
            'form' => $form->createView()
        ));
    }

    /**
     * @param Request $request
     * @param Media $media
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function editAction(Request $request, Media $media)
    {
        $em = $this->getDoctrine()->getManager();

        $editForm = $this->createForm(MediaType\EditType::class, $media);
        $editForm->handleRequest($request);
        $restaurant = $media->getRestaurant();

        if ($editForm->isSubmitted() && $editForm->isValid()) {
            $imageFile = $request->files->get('edit')['name'];
            $targetDir = $this->getParameter('uploaded_restaurants');
            $imageName = $this->get('app.uploader')->upload($imageFile, $targetDir);

            if ($request->files->get('edit')['name'] != null) {

                $fs = new Filesystem();
                try {
                    $fs->remove($this->get('kernel')->getRootDir() . '/../web/uploads/restaurants' . $media->getName());
                } catch (IOException $e) {
                    echo "error";
                }

                /** @var $originalName */
                $originalName = $imageFile->getClientOriginalName();
                $media->setName($imageName)
                    ->setOriginalName($originalName)
                    ->setUpdatedAt(new \DateTime());
            }
            $em->persist($media);
            $em->flush();

            return $this->redirectToRoute('admin_restaurant_show_fr', array('id' => $restaurant->getId()));
        }
        return $this->render('admin/restaurant/media/edit.html.twig', array(
            'media' => $media,
            'restaurant' => $restaurant,
            'editForm' => $editForm->createView()
        ));
    }

    /**
     * @param Media $media
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function deleteAction(Media $media)
    {
        $restaurant = $media->getRestaurant();
        $em = $this->getDoctrine()->getManager();
        $em->remove($media);
        $em->flush();

        return $this->redirectToRoute('admin_restaurant_show_fr', array('id' => $restaurant->getId()));
    }
}

如您在 editAction 中所见,我尝试添加 Filesystem 以删除文件

我的问题

如何为我的 editActiondeleteAction 执行此操作,以便从目录中正确删除我的文件? 如果您真的不理解我的代码,是否有一个可以向我展示的示例? 谢谢

无论是编辑还是删除媒体,您都可以使用现有对象及其文件名,例如:

public function deleteAction(Media $media){ ... }

Doctrine 将从 url 中读取 id 并从数据库中加载相应的媒体。您可以使用此对象获取旧图像位置,然后删除该图像。

// getName() will contain the complete filename with path.
// Check your showAction where you call `setName($imageName)`
$filename = $media->getName();

$filesystem = new Filesystem();
$filesystem->remove($filename);

您可以在 editAction 而不是您提供的代码中执行相同的操作。

config/services.yaml

parameters:
      img_dir: "%kernel.project_dir%/public/img"
      public_dir: "%kernel.project_dir%/public"

控制器编辑

public function edit(Request $request, Layanan $layanan, EntityManagerInterface $entityManager): Response
{
// ....
    $file = $form->get('image')->getData();
    $fs = new Filesystem();
    if ($form->isSubmitted() && $form->isValid()) {
        if ($file) {
            $fname = $layanan->getImage();
            $fs->remove($this->getParameter('public_dir').'/img/'.$fname);
            $newFilename = $originalfilename . '-' . uniqid() . '.' . $file->guessExtension();
            try {
                $file->move(
                    $this->getParameter('img_dir'),
                    $newFilename
                );
            } catch (FileException $e) {
                // ... handle exception if something happens during file upload
            }
            $layanan->setImage($newFilename);
        }
//...
}