我正在努力使其在提交图像时,使用CodeIgniter将图像保存到服务器,然后通过jquery在前端显示。
HTML:
<form id="set" method="post" action="<?php echo $base_url; ?>schedule/sample" enctype="multipart/form-data">
<input type="file" name="file" id="file">
<img id="result" src="" width="50" height="50" alt="sample" style="display:hidden;"/>
</form>
JS:
$("#file").change(function() {
var file = this.files[0];
var full = base_url +'public/img/'+ file.name;
$.ajax({
type:'POST',
url:base_url +'schedule/sample',
data:'file='+ file,
success: function() {
$('#result').attr('href', full);
$('#result').fadeIn('fast');
}
});
});
PHP(调度控制器):
public function __construct() {
parent:: __construct();
$base_url = $this->config->base_url();
$this->load->database();
$this->load->model('paypal_model');
$config['upload_path'] = 'public/img/';
$config['allowed_types'] = 'jpg|jpeg';
$config['max_size'] = '1000';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->helper(array('form', 'url'));
$this->load->library('file');
$this->load->library('upload', $config);
$this->load->library('session');
}
public function sample() {
$image = $this->input->post('file');
$base_url = $this->config->base_url();
if(!$this->upload->do_upload('file')) {
$error = array('error' => $this->upload->display_errors());
echo 'not uploaded';
} else {
$pic = $this->upload->data();
print_r($pic);
write_file('public/img/'.$fb_id.'.jpg', $img_data);
$img = $pic['image_width'];
}
}
AJAX不支持文件上传(我想我就是你说的jQuery)。你可以使用类似"隐藏iframe文件上传"的方法(谷歌上有很多教程)来上传AJAX之类的文件。
您必须在CI中创建另一个控制器,该控制器将返回图像数据,或者在公共目录中上载图像(仅在适用的情况下!)。
如果使用控制器,只需设置适当的内容类型标头(例如,内容类型:image/png;)并回显图像文件的内容{get_file_contents}。
此外,如果您想:从"上传"文件的iframe中设置目标图像元素的src属性。