El código que uso es el siguiente:
Controlador:
Código PHP:
public function createAction(Request $request)
{
if ($request->isXmlHttpRequest() && !$request->isMethod('POST')) {
throw new HttpException('XMLHttpRequests/AJAX calls must be POSTed');
}
$entity = new Student();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$file = $entity->getPhoto();
$fileName = md5(uniqid()).'.'.$file->guessExtension();
$photoDir = $this->container->getParameter('kernel.root_dir').'/../web/uploads/images';
$file->move($photoDir, $fileName);
$entity->setPhoto($fileName);
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
if ($request->isXmlHttpRequest()) {
return new JsonResponse(array('message' => 'Success!','success' => true), 200);
}
if ($request->isMethod('POST')) {
return new JsonResponse(array('message' => 'Invalid form','success' => false), 400);
}
return $this->redirect($this->generateUrl('student_show', array('id' => $entity->getId())));
}
return $this->render('BackendBundle:Student:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
Código PHP:
use DoctrineORMMapping as ORM;
use SymfonyComponentValidatorConstraints as Assert;
//...
/**
* @var string
*
* @ORM\Column(name="photo", type="string", length=255, nullable=true)
* @Assert\File(mimeTypes={ "image/png","image/jpg" })
*/
private $photo;
public function setPhoto($photo)
{
$this->photo = $photo;
return $this;
}
public function getPhoto()
{
return $this->photo;
}
Código PHP:
//...
->add('photo', 'file', array('required' => false))
//...
Código PHP:
//...
$('.form_student').on("submit",function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: Routing.generate('student_create'),
data: $(this).serialize(),
dataType: 'json',
success: function(response) {
alert(response.message);
},
error: function (response, desc, err){
if (response.responseJSON && response.responseJSON.message) {
alert(response.responseJSON.message);
}
else{
alert(desc);
}
}
});
});