mysql - 如何将文件添加到数据库 my sql 和 symfony 5
问题描述
我正在尝试将文件上传到我的表单我的上传有问题并出现此错误:
SQLSTATE [23000]:违反完整性约束:1048 列“brochure_filename”不能为空
这是我的代码:DemandeOcontroller:
/**
* @Route("/new", name="demande_o_new", methods={"GET","POST"})
*/
public function new(Request $request): Response
{
$demandeO = new DemandeO();
$form = $this->createForm(DemandeOType::class, $demandeO);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$brochureFile = $form->get('brochure')->getData();
// this condition is needed because the 'brochure' field is not required
// so the PDF file must be processed only when a file is uploaded
if ($brochureFile) {
$originalFilename = pathinfo($brochureFile->getClientOriginalName(), PATHINFO_FILENAME);
dd($originalFilename );
// this is needed to safely include the file name as part of the URL
$safeFilename = $slugger->slug($originalFilename);
$newFilename = $safeFilename.'-'.uniqid().'.'.$brochureFile->guessExtension();
// Move the file to the directory where brochures are stored
try {
$brochureFile->move(
$this->getParameter('brochures_directory'),
$newFilename
);
} catch (FileException $e) {
// ... handle exception if something happens during file upload
echo "file mat3adech";
}
// updates the 'brochureFilename' property to store the PDF file name
// instead of its contents
$demandeO->setBrochureFilename($newFilename);
}
$entityManager->persist($demandeO);
$entityManager->flush();
return $this->redirectToRoute('demande_o_index');
}
return $this->render('demande_o/new.html.twig', [
'demande_o' => $demandeO,
'form' => $form->createView(),
]);
}
需求类型:
->add('brochure', FileType::class, [
'label' => 'Brochure (PDF file)',
// unmapped means that this field is not associated to any entity property
'mapped' => false,
// make it optional so you don't have to re-upload the PDF file
// every time you edit the Product details
'required' =>true,
// unmapped fields can't define their validation using annotations
// in the associated entity, so you can use the PHP constraint classes
'constraints' => [
new File([
'maxSize' => '1M',
'mimeTypes' => [
'application/pdf',
'application/x-pdf',
],
'mimeTypesMessage' => 'Please upload a valid PDF document',
])
],
])
services.yaml 中的配置:
brochures_directory: '%kernel.project_dir%/public/uploads/brochures'
我在 public uploads->brochures 中添加了两个文件夹
解决方案
推荐阅读
- http - 阻止 web.xml 中的一些 HTTP 方法
- python - 如何在pydantic中动态生成属性?
- conv-neural-network - heatmap) ValueError: Input 0 of layer sequence is in compatible with the layer
- html - 如何使用 IntersectionOver API
- server - SNMP 重置后数据会被删除吗?
- python - 导入同名的python模块和扩展模块
- html - R Shiny 应用程序加载,但单选按钮未正确选择值
- java - 概述的方法是 POST,但作为 GET 传递
- java - 使用流将数组转换为地图
- ionic-framework - 我们可以自定义离子吐司中的单个按钮吗