我一直试图通过默认的symfony表单设置文件上传 Symfony的\分量\ HttpFoundation \文件\ UploadedFile的。 我有一个非常简单的形式,有一个输入,文件上传按钮和提交按钮。这是我的控制者:
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,而不是注释。毕竟,我在尝试上传文件时出错:
File.php第37行中的FileNotFoundException: 文件" / tmp / phpFMtBcf"不存在
我做错了什么?
答案 0 :(得分:2)
好的,我仍然没有找到我的问题的答案。我试图在不同的论坛上搜索,在法语:)所以我的解决方案在下一个。我在实际处理请求之前手动收集文件数据,然后处理请求,接下来我做的是,我是复制文件而不是移动。那不是我描述的错误。所以它应该是美丽和方便的重构,但它运作良好。感谢您的关注。
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(),
));
}
}