如何在codeigniter中使用ajax上传图像?

我正在尝试使用jQuery和ajax函数上传图像,如何获取图像文件的所有细节,就像在PHP中我们使用$_FILE()

这是我的代码

JS

 $("#uploadimg" ).click(function() { $( "#file" ).click(); }); $( "#file" ).change(function(e) { var file=$('#file').val(); alert(file); die(); e.preventDefault(); $.ajax({ url:'http://localhost/JSG/blog/uploadimg', secureuri:false, type: "POST", fileElementId:'image', dataType: 'text', data:{ file: file }, cache: true, success: function (data){ alert(data); console.log(data); }, }); }); 

调节器

 public function uploadimg() { $var = $_POST['file']; print_r($var); if($this->input->post('file')) { $config['upload_path'] = 'upload'; $config['file_name'] = $var; $config['overwrite'] = 'TRUE'; $config["allowed_types"] = 'jpg|jpeg|png|gif'; $config["max_size"] = '1024'; $config["max_width"] = '400'; $config["max_height"] = '400'; $this->load->library('upload', $config); if(!$this->upload->do_upload()) { $this->data['error'] = $this->upload->display_errors(); print_r( $this->data['error']); } else { print_r("success"); } } } 

视图

 
<img src="https://stackoverflow.com/questions/27270179/how-can-i-upload-image-with-ajax-in-codeigniter/assest/img/blank.png" alt="Blank image" id="uploadimg" class="img-thumbnail">

响应

C:\ fakepath \ Koala.jpg您没有选择要上传的文件。

请帮忙

您可以在html5中使用FormData api。

您的表格必须是:

 

然后jquery:

 function uploadImage() { if (typeof FormData !== 'undefined') { // send the formData var formData = new FormData( $("#formID")[0] ); $.ajax({ url : baseUrl + 'uploadImage', // Controller URL type : 'POST', data : formData, async : false, cache : false, contentType : false, processData : false, success : function(data) { successFunction(data); } }); } else { message("Your Browser Don't support FormData API! Use IE 10 or Above!"); } } 

然后在控制器中,您将获得$_FILES数组中的文件。

在显示表单的视图中:

添加属性: enctype=multipart/form-data

要么,

如果您要使用表单助手创建表单:

  

如果您在javascript中使用此插件(编写良好),则可以获得无缝function。

http://malsup.com/jquery/form/

用PHP上传文件

  500000) { echo "Sorry, your file is too large."; $uploadOk = 0; } // Allow certain file formats if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) { echo "The file ". basename( $_FILES["file"]["name"]). " has been uploaded."; } else { echo "Sorry, there was an error uploading your file."; } } ?> 

您可以使用Ajaxfileupload.js上传文件:

 $('input[type="file"]').ajaxfileupload({ 'action': 'save_photo.php', 'params': { 'extra': 'info' }, 'onComplete': function(response) { console.log('custom handler for file:'); alert(JSON.stringify(response)); }, 'onStart': function() { }, 'onCancel': function() { console.log('no file selected'); } }); 

save_photo.php: