我无法在我的表单中上传 JPG 图片

I can't upload a JPG image in my form

我使用 Symfony 3.2 并使用仅接受 jpg、jpeg、gif 和 png 扩展名的文件字段构建表单。不幸的是,我无法上传任何带有 .jpg 扩展名的图像,尽管我在允许的 mime 类型中提到了 image/jpeg mime 类型。显示错误 "mimeTypesMessage"。

如果您看一下,我将不胜感激。谢谢

ImageType.php

/**
 * Defines the form used to create and manipulate images.
 *
 * @author XXX
 */
class ImageType extends AbstractType {

    /**
     * Main function of the class.
     * 
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options) {

        $builder
                ->add('title', TextType::class, array(
                    'label' => 'Tytuł',
                    'constraints' => [
                        new Length([
                            'min' => 3,
                            'max' => 128,
                            'minMessage' => 'Tytuł musi posiadać minimum 3 znaki.',
                            'maxMessage' => 'Tytuł może zawierać maksymalnie 128 znaków.',
                        ]),
                    ],
                ))
                ->add('file', FileType::class, array(
//                    'mapped' => false,
                    'constraints' => [
                        new Image([
                            'maxSize' => '2M',
                            'maxSizeMessage' => 'Maksymalny rozmiar obrazka wynosi 2 MB. Wgraj mniejsze zdjęcie.',
                            'mimeTypes' => ['image/jpeg,', 'image/pjpeg', 'image/png', 'image/gif'],
                            'mimeTypesMessage' => 'Nieobsługiwany format pliku. Dozwolone rozszerzenia obrazków to: jpg, gif, png.',
                            'uploadErrorMessage' => 'Dodawanie obrazka zakończyło się niepowodzeniem.',

                            'minWidth' => 1000,
                            'minWidthMessage' => 'Minimalna szerokość obrazka to px',
                            'minHeight' => 1000,
                            'minHeightMessage' => 'Minimalna wysokość obrazka to px',
                            'maxWidth' => 1100,
                            'maxWidthMessage' => 'Maksymalna szerokość obrazka to px',
                            'maxHeight' => 1100,
                            'maxHeightMessage' => 'Maksymalna wysokość obrazka to px',
                        ]),
                    ],
                ))
                ->add('source', TextType::class, array(
                    'label' => 'Źródło',
                    'required' => false,
                ))
                ->add('reset', ResetType::class, array(
                    'label' => 'Reset'
                ))
                ->add('submit', SubmitType::class, array(
                    'label' => 'Zapisz'
                ))
                ;
    }

    /**
     * Configures form options.
     * 
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Object::class,
        ]);
    }    

}

ObjectController.php

public function addImageAction(Request $request) {

    $object = new Object();

    // create form with multiple buttons
    $form = $this->createForm(ImageType::class, $object)
            ->add('saveAndCreateNew', SubmitType::class);

    // fill the object by values from the form (if submitted)
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {

        $file = $object->getFile();

        if(!$file->getError()) {
            $ext = $file->guessExtension();
            if ($ext == 'jpeg') {
                $ext = 'jpg';
            } 

            $object->setName(md5(uniqid()) . '.' . $ext );
            $object->setFile($file->getClientOriginalName());
            $object->setFormat($file->getMimeType());


        } else {
            $this->addFlash('danger', 'Wystąpił nieznany błąd w przesyłaniu formularza. Spróbuj ponownie.');
            return $this->redirectToRoute('app_object_addimage'); 
        }

// rest of form handling...

令我感到奇怪的是,IANA 页面 (http://www.iana.org/assignments/media-types/media-types.xhtml) 上没有列出 image/jpeg mime 类型。不幸的是,我还没有在网上找到问题的解决方案。

尝试使用图像而不是文件。它默认接受所有图像类型并且应该适用于 JPG/JPEG:

http://symfony.com/doc/current/reference/constraints/Image.html#mimetypes

看起来你的问题的原因只是一个小错字。逗号插入错误的地方:

'mimeTypes' => ['image/jpeg,', 'image/pjpeg', 'image/png', 'image/gif'],

我和 $file->guessExtension() 有同样的问题,找不到任何解决方案,和你一样。

直到我找到 $file->guessClientExtension() 函数 here 并且它在与 Symfony 3.3.10 交换后对我有用。

我的代码示例:

$imageForm->add('image', FileType::class, array(
    'label' => false,
    'attr' => array(
        'accept' => "image/*",
        'multiple' => "multiple",
    ),
    'required' => true,
    'multiple' => true,
));

$imageForm->handleRequest($request);

if ($imageForm->isSubmitted() && $imageForm->isValid()) {
    $model = $imageForm->getData();
    $files = $model->getImage();

    foreach($files as $file) {
        $newFileName = $someGeneratedIdentifier.'.'.$file->guessClientExtension();

        $file->move(
            $this->getParameter('directory').'/'.$someSubdirectory,
            $newFileName
        );

...