dsapkqaduj6718493 2017-08-26 10:40 采纳率: 100%
浏览 54
已采纳

Symfony下载后删除文件

I am working on a Symfony application where users can crop images with. After someone has downloaded the cropped image I want the application to remove it from the server.

I currently have this controller action:

/**
 * @Route(
 *      "/download/{crop_id}",
 *      name="download_cropped",
 *      options={"expose"=true}
 * )
 *
 * @ParamConverter(
 *      "crop",
 *      class="WebwijsCropperBundle:Crop",
 *      options={"id" = "crop_id"}
 * )
 *
 */
public function downloadAction(Crop $crop)
{
    $dir = $this->container->getParameter('image.cropped.dir');
    return new BinaryFileResponse($dir . '/' . $crop->getCroppedFile());
}

I created this EventListener where I want to remove the image after the response is sent. This Listener will be triggered after every response.

So how do I get the information that I need to know if the response comes from the correct controller action. And how can I get the crop_id parameter so I know which file to remove?

class FileRemovalListener
{
    private $logger;

    public function __construct(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    public function onKernelTerminate(PostResponseEvent $event)
    {
        $response = $event->getResponse();
        $request = $event->getRequest();
        // what do i have to do here to know 
        // from which controller action the response comes?

    }
}

This is the service definition in services.yml

WebwijsCropperBundle\EventListener\FileRemovalListener:
        tags:
            - { name: kernel.event_listener, event: kernel.terminate, method: onKernelTerminate }
  • 写回答

2条回答 默认 最新

  • douza19870617 2017-08-26 13:24
    关注

    If you only want to remove the file, try this:

    public function downloadAction(Crop $crop)
    {
        $dir = $this->container->getParameter('image.cropped.dir');
        $response = new BinaryFileResponse($dir . '/' . $crop->getCroppedFile());
    
        $response->deleteFileAfterSend(true);
    
        return $response;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据