2018-12-26 04:52
浏览 99

如何使用AJAX将图像发送到Symfony Controller?

I have sent cropped images to Symfony controllers with AJAX using Symfony 3, however I can't achieve the same using Symfony 4 webpack. I achieved it previously using the on('change') method, however that, along with on('click) and on('submit') don't seem to work.

My code is below:

JavaScript app.js

 var routeUrl = Routing.generate('getImage');

 $('#upload_btn').on('click', function(){

            var block = getResponse.split(";");
            // Get the content type
            var contentType = block[0].split(":")[1];// In this case "image/gif"
            // get the real base64 content of the file
            var realData = block[1].split(",")[1];// In this case "iVBORw0KGg...."

            // Convert to blob
            var blob = b64toBlob(realData, contentType);

                    let formData = new FormData(form);
                    formData.append('image_path', blob);
                    url: routeUrl,
                    method: 'POST',
                    data:  formdata,
                    contentType: false,
                    cache: false,
                    headers: {'X-Requested-With':'XMLHttpRequest'},
                    success:  function(data){

                                  $("#previewImg").attr('src', getResponse);

Symfony Controller

* @Route("/getImage", name="getImage", methods={"POST"}, options={"expose"=true})
 * @param Request $request
 * @return JsonResponse
 * @Cache(vary={"X-Requested-With"})

public function gteImageAjax(Request $request){


        $event = new Members();

        $form = $this->createForm(EventType::class, $event);
        /** @var Symfony\Component\HttpFoundation\File\UploadedFile $file */
       // $file = $request->get('image');
        $file = $request->files->get('image_path');

       // $file = new UploadedFile($file['tmp_name'], $file['name'], $file['type']);

        $filename = md5(uniqid()).'.'.$file->guessExtension();

        $file->move($this->getParameter('image_directory'), $filename);

        $em = $this->getDoctrine()->getManager(); 


        return $this->redirectToRoute('createEvent');

    return new JsonResponse("This is not Ajax");

To clarify I want to send the cropped image to my symfony controller using AJAX. Any help will be appreciated.

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题