尝试下载&;使用Symfony2保存PDF文件


Trying To Download & Save A PDF File Using Symfony2

我正在尝试下载&从联机资源中保存PDF文件。我看过关于文件上传的烹饪书章节,并尝试修改该技术以供自己使用。我就是做不到。

控制器代码:

namespace Acme'DemoBundle'Controller;
use Symfony'Bundle'FrameworkBundle'Controller'Controller;
use Symfony'Component'HttpFoundation'Request;
use Symfony'Component'HttpFoundation'Response;
use Acme'DemoBundle'Entity'Shipment;
class WelcomeController extends Controller
{
    public function indexAction(Request $request)
    {
        echo $barcodeUrl  = "http://www.website.com/somefile.pdf";
        $Shipment = new Shipment();
        $Shipment->setBarcodeUrl($barcodeUrl);
        $em = $this->getDoctrine()->getEntityManager();
        $em->persist($Shipment);
        $em->flush(); 
        // Saving The File:
        $saveto = __DIR__.'/../../../../web/uploads/documents';
        $ch = curl_init($barcodeUrl);
        $fp = fopen($saveto,'wb');
        curl_setopt($ch, CURLOPT_FILE, $fp);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_exec($ch);
        curl_close($ch);
        fclose($fp); 
        return new Response('Created shipment and saved file");
    }
    protected function getUploadRootDir()
    {
        return __DIR__.'/../../../../web'.$this->getUploadDir();
    }
    protected function getUploadDir()
    {
        return 'uploads/documents';
    }
}

每次我运行上面的代码。它将一个文件保存在web文件夹中,该文件的名称为我提到的路径。该文件不打开,甚至不使用任何扩展名保存。

保存的文件:web文件夹中的/../../../../web/home/webmuch/uploads

这不是一个真正的Symfony2问题。您还需要将文件名传递给fopen。所以应该是这样的:

$fp = fopen(sprintf('%s/%s.%s', $saveto, sha1($barcodeUrl), 'pdf'),'wb');

我还注意到你没有使用getUploadRootDir()方法,我想是因为它对你不起作用——原因是你在中缺少了一个斜杠

protected function getUploadRootDir()
{
    return __DIR__.'/../../../../web/'.$this->getUploadDir();
}

最后但并非最不重要的是,您可以使用$this->container->getParameter('kernel.root_dir').'/../web' 获取网站位置

所以

protected function getUploadRootDir()
{
    return $this->container->getParameter('kernel.root_dir').'/../web/'.$this->getUploadDir();
}