我正在尝试使用 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);
},
});
});
Controller
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 You did not select a file to upload.
请帮忙
最佳答案
您可以在 html5 中使用 FormData api。
您的表格必须是:
<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!");
}
}
然后在 Controller 中,您将获得 $_FILES
数组中的文件。
关于php - 如何在 codeigniter 中使用 ajax 上传图片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27270179/