如何在codeigniter中使用ajax上传文件

我正在尝试使用ajax上传文件和其他参数。 但是,文件没有上传。

表格代码

<input type="image" src="assets/images/icon/_Save.png" class="Save-container img-circle" id="submit_first_form">

脚本代码

  $(document).ready(function() { $("#submit_first_form").click(function(event) { event.preventDefault(); var file = $("input#file").val(); var first_name = $("input#first_name").val(); var last_name = $("input#last_name").val(); jQuery.ajax({ type: "POST", url: "" + "student/add_data", dataType: 'json', data: { file: file, first_name: first_name, last_name: last_name }, success: function(res) { if (res) { console.log(res); } } }); }); });  

控制器代码

 public function add_data() { $data = array( 'file' => $this->input->post('file'), 'first_name' => $this->input->post('first_name'), 'last_name'=>$this->input->post('last_name') ); $status = ""; $msg = ""; $file_element_name = $data['file']; $config['upload_path'] = 'www.localhost.com/project/assets/supplier'; $config['allowed_types'] = 'gif|jpg|png|doc|txt'; $config['max_size'] = 1024 * 8; $config['encrypt_name'] = TRUE; $this->load->library('upload', $config); if (!$this->upload->do_upload($file_element_name)) { $status = 'error'; $msg = $this->upload->display_errors('', ''); } else { $data = $this->upload->data(); //$data['file_name'] $status = "success"; $msg = "File successfully uploaded"; } echo json_encode(array('status' => $status, 'msg' => $msg)); } 

我在控制台中遇到的错误是:

{status:“error”,msg:“您没有选择要上传的文件。”}

任何人都可以告诉如何上传文件

尝试将此代码用于脚本:

  
 

文件上传时的enctype。

– >在表单标签中提供id提交并在表单关闭脚本之前添加一个提交按钮以发送请求$(“#save”)。click(function(event){event.preventDefault();

 // Create an FormData object var data1 = new FormData($('#fileUploadForm')[0]); console.log($('#fileUploadForm')); $.ajax({ type: "POST", enctype: 'multipart/form-data', url: "" + "student/add_data", data: data1, processData: false, contentType: false, cache: false, success: function (data) { data = JSON.parse(data); console.log(data); if(data.id==1) { localStorage.setItem("user_profile_pic", data.user_pic); alert("updated sucessfully") } } });