Symfony2 如何验证通过 AJAX 发送的文件 [英] Symfony2 how to validate files sending via AJAX

查看:26
本文介绍了Symfony2 如何验证通过 AJAX 发送的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我必须对通过ajax发送的文件(有图像)进行验证,我在验证作为注释时遇到了很大的问题,只有当我们发送正常表单时才有效!不是如果文件数据通过 ajax 传入:/那么这是 symfony 的代码,它可以验证我们的文件集合并将错误消息设置为它们的属性路径.

Hi today i must make a validation for files(there images) sending via ajax, i have huge problems with validation as annotation that work only when we send normaly form! not if files data coming via ajax :/ then that is code for symfony that can valid our collection of files and set error messages to their propertyPath.

$validatorImage = new Image(); // Symfony\Component\Validator\Constraints\Image
$validatorImage->mimeTypesMessage = 'image.mimeTypesMessage';
if ($form->isSubmitted()) {
    $i = 0;
    foreach ($form->get('images') as $image) {
        $errorList = $this->get('validator')->validateValue(
            $image->get('file')->getData(),
            $validatorImage
        );

        if (count($errorList)) {
            foreach ($errorList as $error) {
                $image->addError(
                    new FormError(
                        $error->getMessage(),
                        null,
                        array(),
                        null,
                        array('propertyPath' => 'children[images].data['.$i.'].file')
                    )
                );

            }
        }
        $i++;
    }
}

//是有效的等等.我们的 js 动作类似于这个:

// is valid etc. our js action like similar to this one:

  $('form[name="product"]').on('submit', function () {
        var _self = $(this);
        var data = _self.serialize();
        data = new FormData(_self[0]);
        data.append('ajax',true);
        $.ajax({
            method: "POST",
            url: url,
            data: data,
            cache: false,
            contentType: false,
            processData: false,
            enctype: 'multipart/form-data',
            });
            });

推荐答案

您可以在没有表单生成器的情况下验证您的实体.只需知道 validator 本身就是一项服务.您可以在 controller 中使用类似于以下内容:

You can validate your entity without a form builder. Just know that validator is a service itself. You can use similar to something below in your controller :

// Collect data from ajax .
if ($request->isXmlHttpRequest()) {
    $data = $request->get('data');
    $files = $request->files;

    // Prepare your entity, Know you haven't uploaded image yet.
    $image = new Image();
    $image->setFile($files['image']);

    // Call your validator to validate Image Entity.
    $validator = $this->get('validator');
    $errors = $validator->validate($image);

    $errorMessages = array();
    if (count($errors) > 0) {
        foreach ($errors as $error) {
            $errorMessages[] = $error->getMessage();
        }
    }

    // send response to ajax accordingly. $errorMessages has all the errors as string.
    $response = array();
    return new JsonResponse($response);
}

注意:变量和对象可能因您的用例而异.

Note : Variables and objects might be different for your use cases.

希望这会有所帮助!

这篇关于Symfony2 如何验证通过 AJAX 发送的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆