2017-04-27 112 views
0

嘿,大家好,我在symfony3中使用ajax上傳文件時遇到問題我檢測到沒有提交或用ajax,jquery點擊文件的事件,但是我沒有任何東西在方法控制器中獲取請求總是空如何在symfony3中使用ajax jquery上傳文件

第一的console.log(file_data)返回

File {name: "pawandeep.jpg", lastModified: 1489747066000, lastModifiedDate: Fri Mar 17 2017 11:37:46 GMT+0100 (Paris, Madrid), webkitRelativePath: "", size: 30970…} 

最後的console.log(數據)返回NULL!

<form method="post" action="#" id = "myForm" enctype="multipart/form-data" > 
    <div id="mybutton"> 
     <input type="file" id="myfile" name="upload"/> 
      Click Me! 
    </div> 
</form> 
<div class="progress"> 
    <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="width: 100%"> 
    </div> 
</div> 


<script> 
    $(document).ready(function() { 
     $('.progress').hide(); 
     $('#myfile').change(function(evt) { 

      /*srcPhoto = $(this).val();*/ 
      $('.progress').show(); 
      var file_data = $("#myfile").prop("files")[0]; 
      console.log(file_data); 
      var form_data = new FormData(file_data);     // Creating object of FormData class 
      /*form_data.append("file", file_data)*/ 
      /*form_data.append("id", "{{ doctor.id }}")*/ 
      if(file_data != ""){ 
       $.ajax({ 
        url: "{{ path('bonjou', {'id':doctor.id}) }}", // Url to which the request is send 
        type: "POST", // Type of request to be send, called as method 
        data: form_data, // Data sent to server, a set of key/value pairs (i.e. form fields and values) 
        contentType: false, // The content type used when sending data to the server. 
        cache: false, // To unable request pages to be cached 
        processData: false, // To send DOMDocument or non processed data file it is set to false 
        mimeType: "multipart/form-data", 
        dataType:"json", 
        success: function (data) // A function to be called if request succeeds 
        { 
         $(".progress").hide(); 
         console.log(data); 
         $(".photoDoctor").attr("src", data.name); 
        } 
      }); 
      }; 
     }); 
    }); 
</script> 

文件生根

bonjou: 
    path: /akrem/{id} 
    defaults: { _controller: DoctorsAdminBundle:Doctor:akrem } 

方法控制

public function akremAction(Request $request, $id) 
{ 
    $em = $this->getDoctrine()->getManager(); 
    $doctor = $em->getRepository('DoctorsAdminBundle:Doctor')->find($id); 
    $file = $request->files->get('upload'); 
    $countryArray = array(
     'file'=>$file 
    ); 
    return new \Symfony\Component\HttpFoundation\JsonResponse($countryArray); 
} 

回答

0

更改腳本

<script> 
$(document).ready(function() { 
    $('.progress').hide(); 
    $('#myfile').change(function(evt) { 

     /*srcPhoto = $(this).val();*/ 
     $('.progress').show(); 
     var file_data = $("form")[0]; 
     console.log(file_data); 
     var form_data = new FormData(file_data);     // Creating object of FormData class 
     /*form_data.append("file", file_data)*/ 
     /*form_data.append("id", "{{ doctor.id }}")*/ 
     if(file_data != ""){ 
      $.ajax({ 
       url: "{{ path('bonjou', {'id':doctor.id}) }}", // Url to which the request is send 
       type: "POST", // Type of request to be send, called as method 
       data: form_data, // Data sent to server, a set of key/value pairs (i.e. form fields and values) 
       contentType: false, // The content type used when sending data to the server. 
       cache: false, // To unable request pages to be cached 
       processData: false, // To send DOMDocument or non processed data file it is set to false 
       mimeType: "multipart/form-data", 
       dataType:"json", 
       success: function (data) // A function to be called if request succeeds 
       { 
        $(".progress").hide(); 
        console.log(data); 
        $(".photoDoctor").attr("src", data.name); 
       } 
     }); 
     }; 
    }); 
}); 

+0

無第一個console.log(file_data)返回undefined !! –

+0

你正在嘗試傳遞文件individualy nstead嘗試通過整個表單,它會得到你的結果 –

+0

虐待示例 –

0
function SubmitForm() { 
     var data = $("#policyForm").serialize(); 
     var url = "/Policies/NewPolicy" 
     var form = $('#policyForm')[0] 
     var formdata = false; 
     if (window.FormData) { 
      formdata = new FormData(form); 
     } 
     $.ajax({ 
      url: url, 
      type: 'POST', 
      dataType: 'json', 
      data: formdata ? formdata : data, 
      cache: false, 
      contentType: false, 
      enctype: 'multipart/form-data', 
      processData: false, 
      success: function (data) {//Your successcode} 
+0

我得到了這個結果{「files」:[]} –

0

我想給你的答案,它工作正常我享受!

樹枝視圖

<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12"> 
             {#<button type="button" id="mybutton" class="updatePhotoDoctor btn btn-default arabe">تعديل</button>#} 
             {{ form_start(editPicForm, {"attr":{"id":"akrem"}}) }} 
             <div class="form-group"> 
              {#Génération du label. #} 
              {{ form_label(editPicForm.photoDoctor, "صورة الطبيب", {'label_attr': {'class': 'arabe control-label'}}) }} 

              {#Affichage des erreurs pour ce champ précis.#} 
              {{ form_errors(editPicForm.photoDoctor) }} 
              {#Génération de l'input.#} 
              {{ form_widget(editPicForm.photoDoctor, {'attr': {'class': 'arabe'}}) }} 
             </div> 
             {#<div class="form-group"> 
              Génération du label. 
              {{ form_label(editPicForm.password, "كلمة المرور", {'label_attr': {'class': 'arabe control-label'}}) }} 

              Affichage des erreurs pour ce champ précis. 
              {{ form_errors(editPicForm.passwordDoctor) }} 
              Génération de l'input. 
              {{ form_widget(editPicForm.passwordDoctor, {'attr': {'class': 'arabe'}}) }} 
             </div>#} 
             <div class="progress"> 
              <div class="progress-bar progress-bar-striped progress-bar-animated" 
               role="progressbar" aria-valuenow="100" aria-valuemin="0" 
               aria-valuemax="100" style="width: 100%"></div> 
             </div> 
             <input type="submit" value="تعديل"/> 
             {{ form_end(editPicForm) }} 

            </div> 

腳本AJAX

<script> 
    $(document).ready(function() { 
     $('.progress').hide(); 
     $('#akrem').on("submit", function (event) { 
      event.preventDefault(); 
      $('.progress').show(); 
      $.ajax({ 
       type: 'POST', 
       url: "{{ path('doctors_admin_editPhotoDoctor', {'id':doctor.id}) }}", 
       data: new FormData($(this)[0]), 
       dataType: 'json', 
       processData: false, 
       cache: false, 
       contentType: false, 
       success: function (response) { 
        console.log(response.photo); 
        $('#doctorPic').attr('src', '{{ asset('uploads/doctors/') }}' + response.photo); 
        $('.doctorPic').attr('src', '{{ asset('uploads/doctors/') }}' + response.photo); 
        /*alert(response.message); 
        console.log(response);*/ 
        $('.progress').hide(); 
       }, 
       error: function (response, desc, err) { 
        if (response.responseJSON && response.responseJSON.message) { 
         alert(response.responseJSON.message); 
        } 
        else { 
         alert(desc); 
        } 
       } 
      }); 
     }); 
    }); 
</script> 

路由

doctors_admin_editPhotoDoctor: 
    path:  /editPhotoDoctor/{id} 
    defaults: { _controller: DoctorsAdminBundle:Doctor:editPhotoDoctor } 
    requirements: 
     id: \d 

控制器

public function editPhotoDoctorAction(Request $request, Doctor $doctor) 
{ 

    $editPictureForm = $this->createForm('Doctors\AdminBundle\Form\EditPictureDoctorType', $doctor); 
    $editForm = $this->createForm('Doctors\AdminBundle\Form\EditDoctorType', $doctor); 
    $editPictureForm->handleRequest($request); 
    if ($editPictureForm->isSubmitted()) { 
     $file = $doctor->getPhotoDoctor(); 
     $doctor->setPhotoDoctor($file); // Store the current value from the DB before overwriting below 
     /*if ($file instanceof UploadedFile) {*/ 
     $fileName = md5(uniqid()).'.'.$file->guessExtension(); 
     $file->move(
      $this->getParameter('photoDoctor_directory'), 
      $fileName 
     ); 
     $doctor->setPhotoDoctor($fileName); 
     /*}*/ 
     $this->getDoctrine()->getManager()->flush(); 
     if ($request->isXmlHttpRequest()) { 

      return new JsonResponse(array('message' => 'Success!','success' => true, 'photo'=>$doctor->getPhotoDoctor()), 200); 

     } 
     $session = $request->getSession(); 
     $session->getFlashBag()->add('msg', 'تم تعديل معلومات الطبيب بنجاح'); 
     return $this->redirectToRoute('doctors_admin_doctors'); 
    } 
    /*var_dump($editForm->getErrors());*/ 
    return $this->render('DoctorsAdminBundle:Doctor:editDoctor.html.twig', array(
     'doctor' =>$doctor, 
     'edit_form' =>$editForm->createView(), 
     'editPicForm'=>$editPictureForm->createView(), 
    )); 

}