如何使用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

 Routing.setRoutingData(Routes)
 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);
                    $.ajax({
                    url: routeUrl,
                    method: 'POST',
                    data:  formdata,
                    contentType: false,
                    cache: false,
                    processData: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){


    if($request->isXmlHttpRequest()){

        $event = new Members();

        $form = $this->createForm(EventType::class, $event);
        $form->handleRequest($request);
        /** @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);

        $event->setImage($filename);  
        $em = $this->getDoctrine()->getManager(); 
        $em->persist($event);

        $em->flush();

        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个回答



将表单提供给FormData,指定数据</ p>

  // whole  form 
let formData:new FormData($(form)[0]);

//指定
var formData = new FormData();
formData.append('category','general');
\ n // file
var blob = $('input [type = file]')[0] .files [0]);
formData.append('image_path',blob);

//发送请求 通过AJax
$ .ajax({
url:routeUrl,
data:formData,
type:'POST',
contentType:false,//需要jQuery 1.6+
processData:false,//必需

cn = false,
success:function(data){

$(“#previewImg”)。attr('src',getResponse);
}
});
</ code> </ pre>

你做得很好,只需检查你的ajax请求中的var formData,你就是声明formData并发送formdata </ p>

更改此</ p >

  data:formdata,
</ code> </ pre>

此</ p>

 数据:  formData,
</ code> </ pre>
</ div>

展开原文

原文

Give your form to FormData, specifying the data or not

// whole form    
let formData: new FormData($(form)[0]);

//specifying
var formData = new FormData();
formData.append('category', 'general');

// file
var blob = $('input[type=file]')[0].files[0]);
formData.append('image_path', blob);

//send the request via AJax
$.ajax({
    url: routeUrl,
    data: formData,
    type: 'POST',
    contentType: false, // requires jQuery 1.6+
    processData: false, // required
    cache: false,
    success:  function(data){

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

You're doing good, just check your var formData in your ajax request, you are declaring formData and sending formdata

change this

data:  formdata,

to this

data: formData,

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐