【问题标题】:Upload Image on S3 using SonataMediaBundle with Symfony RestApi using FormType使用 SonataMediaBundle 和 Symfony Rest Api 使用表单类型在 S3 上上传图像
【发布时间】:2017-06-19 11:35:07
【问题描述】:

我正在使用 SonataMediaBundle 在 Symfony Rest API 中上传图像。我在 json 请求中发送 base64Encoded Image 并在我的 FormType 中添加以下代码:

$builder->add( 'subject' )
->add('promotionImage', 'sonata_media_type', array(
'provider' => 'sonata.media.provider.image',
'context' => 'offer',
'required'=>false,
'validation_groups' => 'Default'
));

当我没有为网站添加验证时,我每次都发现验证错误。我每次都会收到这个回复。

{
    "code": 400,
    "message": "Validation Failed",
    "errors": {
        "errors": [
            "This value is not valid."
        ],
        "children": {
            "emailSubject": {},

            "promotionImage": {
                "children": {
                    "binaryContent": {},
                    "unlink": {}
                }
            }
        }
    }
}

非常感谢您的帮助。

【问题讨论】:

    标签: amazon-s3 fosrestbundle symfony-2.8 sonata-media-bundle


    【解决方案1】:

    我已经解决了这个问题。对于使用表单类型上传图像,我们需要添加PRE_SUBMIT 事件监听器,我们需要在其中解码图像内容并将该文件上传到临时位置并以二进制内容传递,因为 Sonata Media Bundle 需要图像资源。我在下面分享我的工作代码以供参考。

     public function buildForm( FormBuilderInterface $builder, array $options )
        {
        $builder->->add(
                        'promotionImage',
                        'sonata_media_type',
                        array(
                            'provider' => 'sonata.media.provider.image',
                            'context'  => 'promotions',
                        )
                    );
        $builder->addEventListener(
                FormEvents::PRE_SUBMIT,
                function ( FormEvent $event ) {
                    $offer = $event->getData();
    
        if ( $offer[ 'promotionImage' ][ 'binaryContent' ] != '' ) {
                if ( preg_match('/data:([^;]*);base64,(.*)/', $offer[ 'promotionImage' ][ 'binaryContent' ])) {
                            $explodeImageData = explode( ',', $offer[ 'promotionImage' ][ 'binaryContent' ] );
                    preg_match("/^data:image\/(.*);base64/i",$offer[ 'promotionImage' ][ 'binaryContent' ], $match);
                    $extension = $match[1];
                    $data = base64_decode( $explodeImageData[ 1 ] );
                    $file = rtrim(sys_get_temp_dir(), '/') . '/' . uniqid() . '.' . $extension;
                    file_put_contents( $file, $data );
                    $offer[ 'promotionImage' ][ 'binaryContent' ] = UploadedFile( $file, $file );
                    } else {
                                throw new \Exception( 'Binary Content is not valid' );
                            }
                }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-30
      • 1970-01-01
      • 1970-01-01
      • 2015-09-20
      • 1970-01-01
      • 1970-01-01
      • 2020-04-30
      • 2015-01-10
      相关资源
      最近更新 更多