Symfony2 文件系统 - 在现有目录中保存数据流

Symfony2 Filesystem - Save a stream of data in an existent directory

我有一个数据流需要保存在 PDF 文件中,然后将该文件存储在一个已经存在的目录中,即 Documents/pdf。该目录与srcappweb目录同级,具有全部写入权限。

在我的解决方案中,我总是将文件保存在 web 目录下。我希望文件位于 Documents/pdf 下。这是我的控制器:

    /**
    * @Route("/api/savePdf", name = "save_pdf")
    * @Method("POST")
    **/
    public function savePdfAction(Request $request) {

        $pdfPath = $this->get("kernel")->getRootDir() . '/../Documents/pdf/';
        $data = $request->getContent();
        $name = 'file.pdf';
        $dateNow = new \DateTime('now');
        $date = $dateNow->format('Y-m-d H-i-s');
        $fileName = $date.$name;

        try {
            $fs = new Filesystem();
            $fs->dumpFile($fileName, $data);
            move_uploaded_file($fileName, $pdfPath.$fileName);
            return new Response ("File saved correctly", 200, array('Content-Type' => 'application/json') );
        }

        catch(IOException $e) {
            return new Response ("Error!", 500, array('Content-Type' => 'application/json'));
        }

        return new Response();
     }

不要使用

move_uploaded_file

http://php.net/manual/en/function.move-uploaded-file.php

This function checks to ensure that the file designated by filename is a valid upload file (meaning that it was uploaded via PHP's HTTP POST upload mechanism).

我只是在猜测,但由于您自己将内容转储到文件中,我认为它不满足 move_uploaded_file 使用条件。

为什么不直接将内容转储到目标文件夹中并摆脱手动移动?

$fs->dumpFile($pdfPath.$fileName, $data);

应该可以解决问题,因为无论如何您的路径都是绝对的。