我尝试使用Symfony 5.4及其文档上传文件。当我提交我的表单时,我有我的表单ProjectType Please upload a valid JPG/PNG file
的约束消息,而它是一个png文件。
我的代码
// Entity\Project.php
public function getImage(): ?string
{
return $this->image;
}
public function setImage(string $image): self
{
$this->image = $image;
return $this;
}
// =============================================
// Form\ProjectType.php
->add('image', FileType::class , [
"attr" => [
"class" => "form-control"
],
"required" => "false",
"mapped" => true ,
'constraints' => [
new File([
'maxSize' => '1024k',
'mimeTypes' => [
'application/png',
'application/jpeg',
],
'mimeTypesMessage' => 'Please upload a valid JPG/PNG file',
])
],
])
// =====================================================
// Controller\ProjectController.php
if($form->isSubmitted() && $form->isValid()){
$em = $this->getDoctrine()->getManager() ;
// Immage file
$img = $form->get('image')->getData() ;
if($img){
$original = pathinfo($img->getClientOriginalName() , PATHINFO_FILENAME) ;
$saveFile = $slugger->slug($original) ;
$newFileName = $safeFileName.'-'.uniqid().'.'.$img->guessExtension() ;
try{
$img->move(
$this->getParameter('image_file_directory'),
$newFileName
) ;
catch (FileException $e){
// ... handle exception if something happens during file upload
}
}
$project->setImage($newFileName) ;
1条答案
按热度按时间8wtpewkr1#
你需要使用
而不是
实际上,一些扩展有许多对应的mimetype。理想情况下,您需要列出所有这些文件,否则用户可以上传 *.jpg文件,但它仍然不会被接受。
为了保持它的简单性和可扩展性,你可以创建一个这样的函数(你可以将$fileTypes数组提取到配置中):
$label.'help'
的转换值应为我的示例应该可以很好地为Symfony和框架使用它像Pimcore。