我正在创建使用 Codeigniter 和 jquery Ajax 自动上传图片的功能。用户将从他们的计算机中选择他们的图像,然后 Ajax 将通过发布发送到服务器。
问题:图片无法上传到服务器,在 Ajax 响应后,我收到了一个空的图片属性。似乎我的表格无效,但我仍然无法找到解决方案。
结果:在Ajax响应后,我的 res 变量无法获取任何数据。
这是我的控制器
public function upload() {
$this->load->helper(array('form', 'url'));
$config['upload_path'] = './uploads/';
$config['image_library'] = 'gd2';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
$token = $this->security->get_csrf_hash();
$data = array();
$res = FALSE;
if (!$this->upload->do_upload('userfile')) {
// $data = $this->upload->data();
$res = FALSE;
} else {
$res = TRUE;
$this->upload->do_upload('userfile');
$data = $this->upload->data();
}
echo json_encode(array('res'=>$res,'img_pro'=>$data,'token'=>$token));
}
这是我的表格
<?php echo form_open_multipart('image/upload', array("class" => "form_horizontal", "id" => "images")); ?>
<div class="col-lg-12 col-sm-12 col-xs-12 ">
<div class="control-group" style="margin-top: 12px;height: 70px; width:100%;border:1px solid red;">
<div class="controls form-group-sm">
<span class="btn btn btn-success btn-lg btn-file">
Select your images: <?PHP echo form_upload('userfile', '', 'id="userfile" class="userfile"') ?>
</span>
</div>
</div>
</div>
<?php echo form_close(); ?>
这是我的Ajax
<script type="text/javascript">
$(document).ready(function () {
$("#images input[name=userfile]").change(function () {
$.ajax({
type: "post",
url: "<?php echo base_url('image/upload'); ?>",
data: {
'<?PHP echo $this->security->get_csrf_token_name(); ?>': '<?PHP echo $this->security->get_csrf_hash(); ?>',
userfile: $("#userfile").val()
},
dataType: "json",
cache: false,
success: function (data) {
console.log(data);
console.log($("#userfile").val());
}
});
});
});
</script>
这是输出
{
"res":false,
"img_pro":{
"file_name":"",
"file_type":"",
"file_path":".\/uploads\/",
"full_path":".\/uploads\/",
"raw_name":"",
"orig_name":"",
"client_name":"",
"file_ext":"",
"file_size":null,
"is_image":false,
"image_width":null,
"image_height":null,
"image_type":"",
"image_size_str":""
},
"token":"7a3f48fc1d4bec708e2ab338ddf96038"
}
答案 0 :(得分:5)
$("#userfile").change(function (objEvent) {
var objFormData = new FormData();
// GET FILE OBJECT
var objFile = $(this)[0].files[0];
// APPEND CSRF TOKEN TO POST DATA
objFormData.append('<?= $this->security->get_csrf_token_name(); ?>', '<?= $this->security->get_csrf_hash(); ?>');
// APPEND FILE TO POST DATA
objFormData.append('userfile', objFile);
$.ajax({
url: "<?= base_url('image/upload'); ?>",
type: 'POST',
contentType: false,
data: objFormData,
//JQUERY CONVERT THE FILES ARRAYS INTO STRINGS.SO processData:false
processData: false,
success: function (data) {
}
});
});