Reputation: 343
I've been trying to setup file upload via default symfony form and Symfony\Component\HttpFoundation\File\UploadedFile. I have really trivial form, with one input, button for file upload and submit button. Here is my conroller:
class DefaultController extends Controller
{
public function uploadAction(Request $request)
{
$document = new Elements();
$form = $this->createFormBuilder($document)
->add('name')
->add('file')
->add('save', SubmitType::class, array('label' => 'Create Task'))
->getForm();
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$document->upload();
$em->persist($document);
$em->flush();
return $this->redirectToRoute('felice_admin_upload');
}
return $this->render('FeliceAdminBundle:Default:upload.html.twig', array(
'form' => $form->createView(),
));
}
}
And I have also created an entity, to persist data to database. I'm using doctrine. Everything that I did, was by manual: http://symfony.com/doc/current/cookbook/doctrine/file_uploads.html
But the only exception was that I used yml, not annotations. After all, I have an error, when trying to upload file:
FileNotFoundException in File.php line 37: The file "/tmp/phpFMtBcf" does not exist
What I am doing wrong?
Upvotes: 3
Views: 1502
Reputation: 343
Ok, I'm still haven't found an answer for my question. I've tried to search on different forums, in on French :) So my solutions in next. I gather file data manually, before actually handling a request, then I handle a request and next thing what I do, is I copy my file instead of moving. That is not getting my described error. So it should be quite refactored for beauty and convenience, but it works well. Thank you for attention.
class DefaultController extends Controller
{
/**
* @Route("/product/new", name="app_product_new")
*/
public function newAction(Request $request)
{
$product = new Product();
$form = $this->createFormBuilder(null, array('csrf_protection' => false))
->add('pic', FileType::class, array('label' => 'Picture'))
->add('Send', 'submit')
->getForm();
$pic = $request->files->get("form")["pic"];
$form->handleRequest($request);
if ($form->isValid()) {
// $file stores the uploaded PDF file
/** @var \Symfony\Component\HttpFoundation\File\UploadedFile $file */
$file = $pic;
// Generate a unique name for the file before saving it
$fileName = md5(uniqid()) . '.' . $pic->guessExtension();
// Move the file to the directory where brochures are stored
$brochuresDir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads';
copy($pic->getPathname(), $brochuresDir . "/" . $fileName);
// Update the 'brochure' property to store the PDF file name
// instead of its contents
$product->setPic($fileName);
// ... persist the $product variable or any other work
return $this->redirect($this->generateUrl('app_product_new'));
}
return $this->render('FeliceAdminBundle:Default:index.html.twig', array(
'form' => $form->createView(),
));
}
}
Upvotes: 2