Symfony 4 - How to save images with FormBuilder (FileType) in Base64 in the Database (MySQL)?

0

Hello, I'm trying to make a form where the user just inserts an image. In theory, the image should be stored as a Blob (Base64) file in the Database, however, Symfony is storing "tmp / php / random value" in the "photo" field of the credential table. I do not know if something is missing, because with return $this->json($credencial->getFoto()) , the returned is actually a Base64 string.

Credential:

class Credencial {
    /**
    * @ORM\Column(name="foto", type="blob")
    */
    protected $foto;

    public getFoto() {
        return $this->foto();
    }

    public setFoto($foto) {
        $this->foto = $foto;
    }
}

CredentialType:

class CredencialType extends AbstractType {
    protected $router;

    public function __construct(RouterInterface $router) {
        $this->router = $router;
    }

    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder
        ->add('foto', FileType::class, array(
            'label' => 'Foto',
            'required' => false
        ))->add('save', SubmitType::class, array(
            'label' => 'SALVAR',
            'attr' => ['class' => 'btn btn-info']
        ));
    }
}

Credential RouteController for adding new credentials:

 /**
 * @Route("/credencial/add", name="credencial_add")
 * @Template()
 */
public function add(Request $request) {
    $credencial = new Credencial();
    $form = $this->createForm(CredencialType::class, $credencial);
    $form->handleRequest($request);

    if($form->isSubmitted() && $form->isValid()) {
        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->persist($credencial);
        $entityManager->flush();

        return $this->redirectToRoute('credencial_add');
    }

    return ['form' => $form->createView()];
}

All help is welcome, thank you in advance!

    
asked by anonymous 06.12.2018 / 18:46

1 answer

1

Actually what $form["foto"] is an instance of UploadedFile, such as fajuchem said. the return $this->json($form["foto"]->getData()); made the conversion automatically to string, so it returned the base64 string of the image, and to save to the Database it is necessary to use file_get_contents , which reads the contents of a file and receives as a parameter the directory of that file, which by the way, was what $form["foto"] owned and was storing it in DB.

    
07.12.2018 / 19:14