错误约束上传图像文件Symfony 5

发布于 2025-02-14 01:30:26 字数 1631 浏览 1 评论 0原文

我尝试使用Symfony 5.4及其文档上传文件。提交表单时,我的表单projectType 的约束消息请上传有效的JPG/PNG文件,而它是一个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() ;
            
// Image 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) ; 

I try to upload files with Symfony 5.4 and its documentation. When I submit my form, I have the constraint message of my form ProjectType Please upload a valid JPG/PNG file whereas it's a png file..

Here my code:

// 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() ;
            
// Image 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) ; 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

灰色世界里的红玫瑰 2025-02-21 01:30:26

您需要使用

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

而不是

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

实际上使用,有些扩展具有许多相应的模拟型。理想情况下,您需要列出所有内容,否则用户可以上传 *.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的翻译值。

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

为了使其保持简单且可扩展以后 使用它像pimcore一样,适用于符号和框架。

You need to use

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

instead of

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

Indeed, some extensions have many corresponding mimetypes. Ideally, you need to list them all otherwise user can upload *.jpg file and it still would not be accepted.

To keep it simple and extendable for future, you can create a function like that (you can extract $fileTypes array to configuration):

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

translation value for $label.'help' should be like

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

My sample should work fine for Symfony and frameworks using it like Pimcore.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文