2017-03-16 53 views
0

我想通過ajax上傳圖片。在客戶端我使用這個代碼。通過ajax上傳圖片時出現錯誤

$(document).on('change','.image_upload',function(){ 
     readURL(this); 
    }); 
    /// 
    function readURL(input) { 
      if (input.files && input.files[0]) { 
       var reader = new FileReader(); 
       reader.onload = function (e) { 


        save_profile_image(e.target.result); 


       } 

       reader.readAsDataURL(input.files[0]); 
      } 
      else { 
       swal("Sorry - you're browser doesn't support the FileReader API"); 
      } 
     } 

     function save_profile_image(image_data){ 
     var image_code = encodeURIComponent(image_data); 
     $.ajax({ 
      type: "POST", 
      url: '<?=base_url()."Dashboard/new_valet_picture";?>', 
      data:'valet_image='+image_code, 
      success: function(data){ 
       alert('data'); 
      } 
     }); 
    } 

而在客戶端我使用codeigniter將其保存爲圖像。圖像文件被創建,但不會顯示,因爲它包含errors.Here是我的CI功能,這個ajax請求正在發送。

public function new_valet_picture(){ 
     $user = $this->session->user_id; 
     $image_data = $this->input->post('valet_image'); 
     $name= "valet_".$user.time().".png"; 

     $profile_image = str_replace('data:image/png;base64,', '', $image_data); 
     $profile_image = str_replace(' ', '+',$profile_image); 
     $unencodedData=base64_decode($profile_image); 
     $pth = './uploads/valet_images/'.$name; 


     file_put_contents($pth, $unencodedData); 

     echo $name; 

    } 

有人可以找出我錯在哪裏。

回答

0

你們正好錯了傳遞參數在Ajax請求:

這是你的代碼

$.ajax({ 
     type: "POST", 
     url: '<?=base_url()."Dashboard/new_valet_picture";?>', 
     data:'valet_image='+image_code, 
     success: function(data){ 
      alert('data'); 
     } 
    }); 

data:'valet_image='+image_code,是錯誤的傳球,並更改到data : {vallet_image : image_code}

0

只是改變的encodeURIComponent()位置幫我

/// 
     function readURL(input) { 
       if (input.files && input.files[0]) { 
        var reader = new FileReader(); 
        reader.onload = function (e) { 


         save_profile_image(encodeURIComponent(e.target.result)); 


        } 

        reader.readAsDataURL(input.files[0]); 
       } 
       else { 
        swal("Sorry - you're browser doesn't support the FileReader API"); 
       } 
      } 

      function save_profile_image(image_data){ 
      var image_code = image_data; 
      $.ajax({ 
       type: "POST", 
       url: '<?=base_url()."Dashboard/new_valet_picture";?>', 
       data:'valet_image='+image_code, 
       success: function(data){ 
        alert('data'); 
       } 
      }); 
     }