php 错误约束上传图像文件symfony 5

rqqzpn5f  于 12个月前  发布在  PHP
关注(0)|答案(1)|浏览(100)

我尝试使用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) ;
8wtpewkr

8wtpewkr1#

你需要使用

'image/png', 'image/jpeg', 'image/pjpeg', 'image/*'

而不是

'application/png', 'application/jpeg'.

实际上,一些扩展有许多对应的mimetype。理想情况下,您需要列出所有这些文件,否则用户可以上传 *.jpg文件,但它仍然不会被接受。
为了保持它的简单性和可扩展性,你可以创建一个这样的函数(你可以将$fileTypes数组提取到配置中):

protected function addUploadField(string $fieldName, string $label = ''): void
{
    $label = $label ?: $fieldName;
    $fileTypes = [
        'pdf'  => [
            'application/pdf',
            'application/acrobat',
            'application/nappdf',
            'application/x-pdf',
            'image/pdf',
        ],
        'doc'  => [
            'application/msword',
            'application/vnd.ms-word',
            'application/x-msword',
            'zz-application/zz-winassoc-doc',
        ],
        'docx' => ['application/vnd.openxmlformats-officedocument.wordprocessingml.document'],
        'rtf'  => ['application/rtf', 'text/rtf'],
        'jpg'  => ['image/jpeg', 'image/pjpeg', 'image/*'],
        'png'  => ['image/png'],
        'tif'  => ['image/tiff'],
        'tiff' => ['image/tiff'],
    ];
    $mimeTypes = array_unique(
        array_filter(
            array_reduce(
                $fileTypes, 
                function ($ext, $types) {
                    return array_merge($ext, $types);
                },
                []
            )
        )
    );
    $extensions = implode(', ', array_unique(array_keys($fileTypes)));
    $maxSize = '25M';
    $translator = $this->translator();
    $this->builder->add(
        $fieldName,
        Type\FileType::class,
        [
            'label'       => $label,
            'help'        => substr(
                $translator->trans(
                    $label.'help',
                    ['%extensions%' => $extensions, '%maxSize%' => $maxSize]
                ),
                0,
                190
            ),
            'required'    => true,
            'multiple'    => true,
            'attr'        => [
                'accept' => implode(', ', $mimeTypes),
            ],
            'constraints' => [
                new All(
                    [
                        'constraints' => [
                            new File(
                                [
                                    'mimeTypes'        => $mimeTypes,
                                    'mimeTypesMessage' => $translator->trans(
                                         $label.'mimeTypesMessage',
                                        ['%extensions%' => $extensions,]
                                    ),
                                    'maxSize'          => $maxSize,
                                ]
                            ),
                        ],
                    ]
                ),
            ],
        ]
    );
}

$label.'help'的转换值应为

'Allowed file formats: %extensions% of size max. %maxSize%.'

我的示例应该可以很好地为Symfony和框架使用它像Pimcore。

相关问题