从Symfony 3

时间:2017-03-20 14:44:25

标签: symfony filesystems delete-file

我的控制器包含createActioneditAction以及deleteAction

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

当我按照Symfony doc创建一个上传文件时,我也在我的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以删除文件

我的问题

如何为我的editAction和我的deleteAction执行此操作,以便从目录中正确删除我的文件? 如果你真的不懂我的代码,你能告诉我一个例子吗? 谢谢

1 个答案:

答案 0 :(得分:3)

在编辑或删除媒体时,您都拥有可用文件名的现有对象,例如:

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中执行相同的操作,而不是您提供的代码。