关于CI上传图片

public function do_upload()
    {
        $config['upload_path']      = './uploads/';
        $config['allowed_types']    = 'gif|jpg|png';
        $config['max_size']     = 100;
        $config['max_width']        = 1024;
        $config['max_height']       = 768;

        $this->load->library('upload', $config);

        if ( ! $this->upload->do_upload('userfile'))
        {
            $error = array('error' => $this->upload->display_errors());

            $this->load->view('upload_form', $error);
        }
        else
        {
            $data = array('upload_data' => $this->upload->data());//这里表示你上传图片的信息,如果说你上传成功就会在页面显示图片的信息

            $this->load->view('upload_success', $data);
        }
    }

在控制器中写上这个方法,在表单提交的时候提交到这个方法,然后在CI 框架的根目录下建一个叫做uploads的文件夹,并且赋予chmod 777权限,这样你就可以去上传你的图片,亲测好使

然后值得注意的是你的form 表单需要写成这样子

<form method="post" action="XXXX/do_upload" enctype="multipart/form-data" />

然后加上这个

<input type="file" name="userfile" size="20" />

</form>

这个页面加上前面控制器的方法,基本就可以满足图片上传的需求,当然具体参考CI框架文档

然鹅,我并不满足于此,你选择的图片你得即时的在页面中显示一下子吧,我多方查找了资料,发现这一段js好使

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#blah').attr('src', e.target.result);
        }
        reader.readAsDataURL(input.files[0]);
    }
}

$("#imgInp").change(function(){
    readURL(this);
});

这块是对应的html

<input type="file" id="imgInp">
<image id="blah" style="width:100px; height:100px;"/>

然后你这样写了之后,就差不多可以实现选择了图片之后即时地显示了 

菜鸟一枚,希望路过大神批评指正

猜你喜欢

转载自blog.csdn.net/fly_on_the_sky/article/details/82967981