I am trying to download & save a PDF file from an online resource. I have seen the cookbook chapter on the File Uploads and tried to modify the technique for my own use. I just can’t get this to work.
Controller Code:
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';
}
}
Every time I run the above code. It saves a file in the web folder, that has the path I have mentioned as it’s name. The file does not open, doesn’t even save with any extension.
Saved File: /../../../../web/home/webmuch/uploads in the web folder.
Not really a Symfony2 problem. You need to also pass a filename to fopen.
So should be something like this:
Also I noticed you have
getUploadRootDir()method that you’re not using, I’m assuming because it didn’t work for you – the reason is that you’re missing a slash in thereLast but not least, you can get web location with
$this->container->getParameter('kernel.root_dir').'/../web'so