2016-01-13 125 views
2

我一直在尝试通过默认的symfony表单设置文件上传和 Symfony \ Component \ HttpFoundation \ File \ UploadedFile。 我真的很平凡的形式,有一个输入,用于文件上传和提交按钮的按钮。这里是我的控制器:无法上传文件通过Symfony 2.8表单上传

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(), 
    )); 
} 
} 

而且我还创建了一个实体,将数据保存到数据库。我在使用教义。我所做的一切,都是通过手动完成的: http://symfony.com/doc/current/cookbook/doctrine/file_uploads.html

但唯一的例外是我使用了yml,而不是注释。毕竟,我有一个错误,试图上传文件时:

FileNotFoundException异常在File.php线37: 文件“/ tmp目录/ phpFMtBcf”不存在

我做错了吗?

回答

1

好的,我仍然没有找到我的问题的答案。我试着在不同的论坛上搜索法语:)所以我的解决方案在下。我在实际处理请求之前手动收集文件数据,然后处理请求,接下来我做的是我复制我的文件而不是移动。这没有得到我描述的错误。所以它应该是美容和便利的重构,但它运作良好。感谢您的关注。

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(), 
    )); 
} 
}