2016-10-25 79 views
3

我正在使用codeigniter 3.1。我想用ajax發佈上傳數據。Ajax上傳不起作用codeigniter

Ajax上傳文件無法正常工作。但是當我發佈沒有Ajax的簡單表單時,它工作正常。

我不知道爲什麼,但在控制檯沒有錯誤。

HTML

<?php echo form_open_multipart(site_url("upload/post"), ['id' => 'uploader']) ?> 
    <input type="file" name="userfile" value=""> 
    <input type="submit" value="Submit" /> 
    <?php echo form_close() ?> 

JAVASCRIPT

$('#uploader').submit(function (event) { 
      event.preventDefault(); 
      $.ajax({ 
       url: window.location.href + '/post', 
       type: "POST", 
       dataType: 'json', 
       data: new FormData(this) 
       }); 
     }); 

CONTROLLERS

public function post() 
    { 
     $this->load->helper('url'); 
     $this->load->helper('form'); 
     $this->load->library("upload"); 
     $file = $this->common->nohtml($this->input->post("userfile")); 

     $this->upload->initialize(array( 
       "upload_path" => 'upload', 
       "overwrite" => FALSE, 
       "max_filename" => 300, 
       "encrypt_name" => TRUE 
      )); 

     $this->upload->do_upload('userfile'); 

     $data = $this->upload->data(); 

     $image_file = $data['file_name']; 

    } 
+0

你是不是傳遞文件上傳類即'$ file'。初始化後,你應該有'if(!$ this-> upload-> do_upload('userfile')){/ * code * /}'。檢查上傳的基本示例[這裏](https://www.codeigniter.com/userguide3/libraries/file_uploading.html#the-controller)。 – Tpojka

+0

我已經試過但沒有工作。 – Mehur

+0

什麼是錯誤? 'var_dump('$ this-> input-> post('userfile'); exit;'檢查PHP是否獲得這些數據。 – Tpojka

回答

1

其中一個問題是文件上傳使用的機制不同於其他形式的<input>類型。這就是爲什麼$this->input->post("userfile")沒有爲你完成工作。其他答案建議使用javascript的FormData,這也是。

HTML

一個非常簡單的形式選擇一個文件,並提交。請注意從簡單按鈕到<input type="submit"...的更改。這樣做使JavaScript更容易使用FormData對象。

FormData documentation

<!DOCTYPE html> 
<html> 
    <head> 
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 
     <script src="https://code.jquery.com/jquery-2.2.2.js"></script> 
     <title>Upload Test</title> 
    </head> 
    <body> 

     <?= form_open_multipart("upload/post", ['id' => 'uploader']); ?> 
     <input type="file" name="userfile"> 
     <p> 
      <input type="submit" value="Upload"> 
     </p> 
     <?php echo form_close() ?> 

     <div id="message"></div> 

     <script> 
      $('#uploader').submit(function (event) { 
       event.preventDefault(); 
       $.ajax({ 
        url: window.location.href + '/post', 
        type: "POST", 
        dataType: 'json', 
        data: new FormData(this), 
        processData: false, 
        contentType: false, 
        success: function (data) { 
         console.log(data); 
         if (data.result === true) { 
          $("#message").html("<p>File Upload Succeeded</p>"); 
         } else { 
          $("#message").html("<p>File Upload Failed!</p>"); 
         } 
         $("#message").append(data.message); 
        } 
       }); 
      }); 
     </script> 
    </body> 
</html> 

JAVASCRIPT

使用FormData捕捉領域。 請注意,不是處理按鈕點擊,我們處理提交事件。

$('#uploader').submit(function (event) { 
    event.preventDefault(); 
    $.ajax({ 
     url: window.location.href + '/post', 
     type: "POST", 
     dataType: 'json', 
     data: new FormData(this), 
     processData: false, 
     contentType: false, 
     success: function (data) { 
      //uncomment the next line to log the returned data in the javascript console 
      // console.log(data); 
      if (data.result === true) { 
       $("#message").html("<p>File Upload Succeeded</p>"); 
      } else { 
       $("#message").html("<p>File Upload Failed!</p>"); 
      } 
      $("#message").append(data.message); 
     } 
    }); 
}); 

控制器

我已經添加了一些代碼,「報告」結果阿賈克斯,並會顯示它上傳頁面上。

class Upload extends CI_Controller 
{ 
    public function __construct() 
    { 
     parent::__construct(); 
     $this->load->helper(['form', 'url']); 
    } 

    public function index() 
    { 
     $this->load->view('upload_v'); 
    } 

    public function post() 
    { 
     $this->load->library("upload"); 
     $this->upload->initialize(array(
       "upload_path" => './uploads/', 
       'allowed_types' => 'gif|jpg|png|doc|txt', 
       "overwrite" => FALSE, 
       "max_filename" => 300, 
       "encrypt_name" => TRUE, 
     )); 

     $successful = $this->upload->do_upload('userfile'); 

     if($successful) 
     { 
      $data = $this->upload->data(); 
      $image_file = $data['file_name']; 
      $msg = "<p>File: {$image_file}</p>"; 
      $this->data_models->update($this->data->INFO, array("image" => $image_file)); 
     } else { 
      $msg = $this->upload->display_errors(); 
     } 

     echo json_encode(['result' => $successful, 'message' => $msg]); 
    } 

} 

這將上傳您的文件。您的工作可能沒有完成,因爲我懷疑您沒有將所需的所有文件信息保存到數據庫。那,我懷疑你會被上傳文件的名字感到驚訝。

我建議你研究一下PHP handles file uploads以及如何檢查文件上傳到SO上的一些類似codeigniter相關的問題。

+0

我不知道爲什麼,但沒有工作.. – Mehur

+0

忘了在答案中提到這一點,但我必須將上傳目錄名稱從'upload'更改爲'uploads'。也許你錯過了那個?除了'data_models-> update()'這是一個模型,我沒有答案代碼爲我工作。當你說,「不工作」。你到底什麼意思? – DFriend

+0

現在感謝您的工作。問題是在我的PHP,但我修好了:) – Mehur

2

試試這個.. 發佈數據使用FormData() formdata post文件也。 要獲取所有表單輸入,包括type="file",您需要使用FormData對象

$('#post').on('click', function (e) { 
    var file_data = $("#userfile").prop("files")[0];  
    var form_data = new FormData();     
    form_data.append("userfile", file_data) 
    $.ajax({ 
      url: window.location.href+'/post', 
      type: 'POST', 
      data: form_data, 
      async: false, 
      success: function (data) { 
       alert(data) 
      }, 
      cache: false, 
      contentType: false, 
      processData: false 
     }); 
    return false; 
}); 

更多... https://abandon.ie/notebook/simple-file-uploads-using-jquery-ajax

+0

好吧,但我有更多的輸入在這種形式,我不想通過阿賈克斯發送。任何方式只發送文件數據? – Mehur

+0

現在檢查我更新的代碼.. –

+0

不工作。獲取'未捕獲的ReferenceError:未定義formData(...)' – Mehur

0

您需要提交的表格,在點擊而是提交...給形式的ID,然後在提交把AJAX

HTML

<?php $attributes = array('id' => 'post'); ?> 

<?php echo form_open_multipart(site_url("upload/post",$attributes), ?> 
    <input type="file" id="userfile" name="userfile" value=""> 
    <button id="post">Submit</button> 
    <?php echo form_close() ?> 

JAVASCRIPT

$( '#郵報')。在( '提交',函數(){

var formData = new FormData(); 
    formData.append("userfile",$("#userfile")[0].files[0]); 

    $.ajax({ 
      url: window.location.href+'/post', 
      type: "POST", 
      data: formData 
     }); 

CONTROLLERS

public function post() 
    { 
     $this->load->library("upload"); 
     $file = $this->common->nohtml($this->input->post("userfile")); 
    $this->upload->initialize(array( 
      "upload_path" => 'upload', 
      "overwrite" => FALSE, 
      "max_filename" => 300, 
      "encrypt_name" => TRUE, 
     )); 

    $data = $this->upload->data(); 

    $image_file = $data['file_name']; 

    $this->data_models->update($this->data->INFO, array(
     "image" => $image_file 
     ) 
    ); 

}

+0

請添加示例(代碼)。 – Mehur

+0

不工作。獲取'上傳:24未捕獲TypeError:無法讀取屬性'0'的undefined(...)1 – Mehur

+0

試試這個...我把這個ID寫錯了 – Araz

3

的另一種方法,這將被傳遞到PHP的base64編碼文件:

  • 使用$('#userfile').prop('files')[0]#userfile領域獲得所選擇的文件;
  • 使用FileReader.readAsDataURL()將該文件的內容轉換爲base64編碼的字符串。我們打電話給這個content;這裏有一個similar question顯示如何做和擴大答案&的可能性;
  • 發送通過filenamecontent字符串的AJAX;
  • 現在在CI上,獲取POST數據;
  • base64_decode()content;
  • 使用filename將結果fwrite()結果到文件中。

這樣你也可以避免發佈所有表單域。

+0

不工作.... – Mehur

+0

究竟發生了什麼? –

+0

獲取錯誤'上傳:24未捕獲TypeError:無法讀取屬性'0'undefined(...)' – Mehur

1

控制器

public function upload() 
{ 
$this->load->library('upload'); 

if (isset($_FILES['myfile']) && !empty($_FILES['myfile'])) 
{ 
    if ($_FILES['myfile']['error'] != 4) 
    { 
     // Image file configurations 
     $config['upload_path'] = './upload/'; 
     $config['allowed_types'] = 'jpg|jpeg|png'; 
     $this->upload->initialize($config); 
     $this->upload->do_upload('myfile'); 
    } 
    } 
} 

查看

<form id="myform" action="<?php base_url('controller/method'); ?>" method="post"> 
<input type="file" name="myfile"> 

("#myform").submit(function(evt){ 
evt.preventDefault(); 

var url = $(this).attr('action'); 
var formData = new FormData($(this)[0]); 
$.ajax({ 
    url: url, 
    type: 'POST', 
    data: formData, 
    processData: false, 
    contentType: false, 
    success: function (res) { 
     console.log(res); 
    }, 
    error: function (error) { 
     console.log(error); 
    } 
}); // End: $.ajax()   

}); // End: submit() 

讓我知道,如果有任何疑問

+0

一個很好的教程在這裏https://code.tutsplus.com/tutorials/how-to-upload-files-with-codeigniter-and-ajax--net-21684 –

+0

http:// stackoverflow .com/questions/27270179/how-can-i-upload-image-with-ajax-in-codeigniter –

+0

Working。謝謝 :) – Mehur