如何在codeigniter上传图像与ajax? [英] How can i upload image with ajax in codeigniter?
本文介绍了如何在codeigniter上传图像与ajax?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试使用Jquery和ajax函数上传图片,我如何使用$ _FILE()来获取图片文件的所有细节。
I'm trying to upload image with Jquery and ajax function,and how can i fetch all details of image file like in php we use $_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");
}
}
}
<form role="form">
<div class="form-group">
<label for="recipient-name" class="control-label">Blog Title:</label>
<input type="text" class="form-control" id="recipient-name">
</div>
<div class="form-group">
<label for="message-text" class="control-label">Message:</label>
<textarea class="form-control" id="message-text"></textarea>
</div>
<div class="form-group">
<label for="message-text" class="control-label">Upload image:</label>
<img src="<?php echo base_url();?>assest/img/blank.png" alt="Blank image" id="uploadimg" class="img-thumbnail">
<input style="display:none" id="file" value=" " type="file" class="file" data-show-preview="false">
</div>
</form>
回应 -
C:\ fakepath \Koala.jpg
您没有选择要上传的文件。
C:\fakepath\Koala.jpg
You did not select a file to upload.
请帮助
推荐答案
您可以在html5中使用FormData api。
You can to use FormData api in html5.
您的表单必须为:
<form enctype="multipart/form-data" accept-charset="utf-8" name="formname" id="formname" method="post" action="">
然后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!");
}
}
然后在控制器中, code> $ _ FILES 数组。
Then in the controller you will get the files in $_FILES
array.
这篇关于如何在codeigniter上传图像与ajax?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文