Skip to content

Instantly share code, notes, and snippets.

@kibao
Last active February 22, 2022 15:14
Show Gist options
  • Save kibao/6982155 to your computer and use it in GitHub Desktop.
Save kibao/6982155 to your computer and use it in GitHub Desktop.
Symfony2 Form Component. Support upload file through API call (e.g. in json, xml, etc.) as base64 encoded content .
<?php
namespace Infun\HttpFoundation\File;
use Symfony\Component\HttpFoundation\File\File;
class ApiUploadedFile extends File
{
public function __construct($base64Content)
{
$filePath = tempnam(sys_get_temp_dir(), 'UploadedFile');
$file = fopen($filePath, "w");
stream_filter_append($file, 'convert.base64-decode');
fwrite($file, $base64Content);
$meta_data = stream_get_meta_data($file);
$path = $meta_data['uri'];
fclose($file);
parent::__construct($path, true);
}
}
<?php
namespace Infun\Controller;
use Symfony\Component\HttpFoundation\Request;
use Infun\Form\Type\PhotoFormType;
use Infun\HttpFoundation\File\ApiUploadedFile;
class Controller {
protected $formFactory;
/* ... */
public function createAction(Request $request)
{
$data = $request->request->all();
/* Process API Upload Request */
if ($request->request->has('photo')) {
$file = new ApiUploadedFile($request->request->get('photo'));
$data['photo'] = $file;
}
$form = $this->formFactory->create(new PhotoFormType());
$form->bind($data);
if ($form->isValid()) {
$photo = $form->get('photo')->getData();
// do with $photo what you want
/* ... */
return $response;
}
/* ... */
// Validation error
return $response;
}
}
<?php
namespace Infun\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints as Assert;
class PhotoFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('photo', 'file', array(
'required' => true,
'constraints' => array(
new Assert\NotBlank(),
new Assert\Image(array(
'mimeTypes' => array('image/jpeg', 'image/png', 'image/x-png', 'image/pjpeg',),
)
),
),
))
;
}
/* ... */
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment