0

I'm trying to make it so that upon submission of an image, the image is saved to the server with CodeIgniter and then displayed on the front end via 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 (Schedule controller):

 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'];

        }
    }
Lance
  • 4,736
  • 16
  • 53
  • 90

1 Answers1

-1

File upload is not supported by AJAX (I think that I what you meant by jQuery). You can use methods like the "hidden iframe file upload" method (google for it, there are many tutorials) to upload files AJAX-like.

The you have to create another controller in CI, which will return image data, or upload the images in a public directory (only if applicable!).

If you use a controller, simply set the appropriate content-type header (e. g. Content-Type: image/png;) and echo the content {get_file_contents} of the image file.

Also, you can do if you want to: set the src attribute of the target image element from the iframe where the file is "uploaded".