2012-08-04 46 views
1

我想下載&保存在線資源中的PDF文件。我已經看到了關於文件上傳的食譜一章,並試圖修改我自己使用的技巧。我只是無法得到這個工作。嘗試使用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/home/webmuch/uploads在web文件夾中。

回答

2

不是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'

所以

斜槓
+0

嘿謝謝你的回答,$ this-> container-> get('kernel.root_dir')給我錯誤:你已經請求了一個不存在的服務「kernel.root_dir」。 – Aayush 2012-08-04 08:16:06

+0

和我以前的方法即使用斜槓也不起作用。 – Aayush 2012-08-04 08:16:57

+0

對不起,應該是$ this-> container-> getParameter('kernel.root_dir') – Inoryy 2012-08-04 08:45:10

相關問題