How to upload a file using ajax / jQuery using symfony2

Can anyone help me?

I am trying to write a script when a user clicks on an image, this leads to an update of the image in the database.

To do this, I wrote code that temporarily makes the Caller Line method in the controller, but when I submit the form, it is not validated due to Cross-Site-Request-Forgery.

$("#upload_picture").on('click', function (e) { e.preventDefault(); $("#bundle_user_file").trigger('click'); }); $("#bundle_user_file").change(function () { if (this.files && this.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $('.active-img').attr('src', e.target.result); }; reader.readAsDataURL(this.files[0]); ajax_formData() } }); 

This is my Caller Line ajax line, performs processing on the form using FormData for publication, will catch routes and token. He calls the route, but is not sure if the image is coming or not, even with the firefox inspector.

 function ajax_formData() { var at = $("form[name=bundle_user]"); var formData = new FormData(); formData.append('file', $("input[type=file]")[0].files[0]); var url = at.attr('action') + '?_token=' + $("#bundle_user__token").val(); $.ajax({ type: "PUT", url: url, data: formData, success: function (data) { alert("success: " + data.message); }, fail: function (data) { alert("error: " + data.message); }, cache: false, contentType: false, processData: false, xhr: function () { // Custom XMLHttpRequest var myXhr = $.ajaxSettings.xhr(); if (myXhr.upload) { // Avalia se tem suporte a propriedade upload myXhr.upload.addEventListener('progress', function () { /* faz alguma coisa durante o progresso do upload */ }, false); } return myXhr; } }); 

}

This is a method in a controlodor with a common button click to send a change to my image. But, as I said before the ajax call, he replied that the token is unavailable

 public function updateAction(Request $request, $id) { $this->denyAccessUnlessGranted('ROLE_USER', null, 'Unable to access this page!'); $em = $this->getDoctrine()->getManager(); $entity = $this->getUser(); if ($entity->getId() != $id) { $response = new JsonResponse( array( 'message' => 'Não tem permissao' ), 400); return $response; } $form_update = $this->updateForm($entity); $form_update->handleRequest($request); if ($form_update->isValid()) { $entity->upload(); $em->persist($entity); $em->flush(); return new JsonResponse(array('message' => 'Success!'), 200); } $response = new JsonResponse( array( 'message' => $form_update->getErrors() ), 400); return $response; } 
-3
source share
2 answers

First, I notice that your click event for #upload_image fires a click trigger on #bundle_user_file, but below that you ask it to look for a change event. Therefore, it will not do anything.

You can regenerate the CSRF token if you want by calling the csrf token_manager service by doing the following:

 /** @var \Symfony\Component\Security\Csrf\CsrfTokenManagerInterface $csrf */ $csrf = $this->get('security.csrf.token_manager'); $token = $csrf->refreshToken($tokenId); return new Response($token); 

You can define $ tokenId in your form if you want, or just use your image id or something else. Typically, a CSRF token is automatically generated from your session, so you can also check it.

+2
source

 function upload_img(){ var file_data = $('.myform').find('.drawing').prop("files")[0]; var form_data = new FormData(); form_data.append("drawing", file_data); $.ajax({ url: "upload.php", type: "POST", data: form_data, contentType: false, dataType:'json', cache: false, processData:false, success: function(data) { }, error: function() { } }); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form class='myform'> <input type='file' class='drawing' onchange='upload_img()' > </form> 
0
source

All Articles