Search code examples
amazon-s3fosrestbundlesymfony-2.8sonata-media-bundle

Upload Image on S3 using SonataMediaBundle with Symfony RestApi using FormType


I am using SonataMediaBundle for image uploading in Symfony Rest API. I am sending base64Encoded Image in json request and added below code in my FormType:

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

I am finding validation error every time while I have not added validation for the site. I'm getting this response every time.

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

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

You help is much appreciated.


Solution

  • I have resolved this issue. For upload images using form type, we need to add PRE_SUBMIT event listener, in which we need to decode the image content and upload that file on temp location and pass it in binary content because Sonata Media Bundle needs image resource. I am sharing my working code as below for the reference.

     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' );
                            }
                }
    }