douxian4323 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

 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条回答 默认 最新

  • dongpouda6700 2018-12-26 13:26
    关注

    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,
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于温度改变石墨烯介电性能(关键词-介电常数)
  • ¥150 HDMI分路器LT86102 的输出在890MHz频点处EMC超标8DB
  • ¥15 druid(相关搜索:数据库|防火墙)
  • ¥15 大一python作业
  • ¥15 preLaunchTask"C/C++: aarch64- apple-darwin22-g++-14 生成活动 文件”已终止,退出代码为-1。
  • ¥60 如何鉴定微信小程序数据被篡改过
  • ¥18 关于#贝叶斯概率#的问题:这篇文章中利用em算法求出了对数似然值作为概率表参数,然后进行概率表计算,这个概率表是怎样计算的呀
  • ¥20 C#上传XML格式数据
  • ¥15 elementui上传结合oss接口断点续传,现在只差停止上传和继续上传,各大精英看下
  • ¥20 手机截图相片分辨率降低一半