jquery image upload: codeigniter

Upload multiple files at once to php server using jquery.

The complete jquery client side code can be found on the following github repository. The code can be easily ported to codeigniter based web site by addading a controller method to handle file uploads on server side. 

https://github.com/blueimp/jQuery-File-Upload

- Select multitple files to upload.

- Drag and drop files to upload on supporting browser. 

- Preview images before uploading. 

- Progressbar while uploading. 

Codeigniter controller

		<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

include_once('sitecontroller.php');
class Media extends SiteController
{


    public function index()
    {

        $userid = $this->checklogin();
        if ($userid > 0) {

            $data['media'] = $this->db->query('select * from media where userid=' . $userid . ' order by id desc');
            $this->load->view('media_view', $data);

        }
    }

    public function show()
    {

        $filename = $this->uri->segment(3);
        $data = $this->getMedia($filename);
        if ($data != null) {
            $this->renderimage($data->path);
        }
    }

    public function show1024()
    {
        $id = $this->uri->segment(3);
        $data = $this->getMedia($id);
        if ($data != null) {
            $this->renderimage($data->path1024);
        }
    }

    public function show800()
    {
        $id = $this->uri->segment(3);
        $data = $this->getMedia($id);
        if ($data != null) {
            $this->renderimage($data->path800);
        }
    }

    public function show400()
    {
        $id = $this->uri->segment(3);
        $data = $this->getMedia($id);
        if ($data != null) {
            $this->renderimage($data->path400);
        }
    }

    public function show100()
    {
        $id = $this->uri->segment(3);
        $data = $this->getMedia($id);
        if ($data != null) {
            $this->renderimage($data->path100);
        }
    }

    public function showthumb()
    {
        $id = $this->uri->segment(3);
        $data = $this->getMedia($id);
        if ($data != null) {
            $this->renderimage($data->paththumb);
        }
    }

    public function get()
    {
        $id = $this->uri->segment(3);
        $data = $this->getMedia($id);
        if ($data != null) {
            $this->load->helper('json');
            echo(json_encode($data));
            return;
        }
        echo("Not found");

    }


    public function save()
    {

        $id = $_POST['id'];
        $title = $_POST['title'];
        $desc = $_POST['desc'];

        $data = array('title' => $title, 'description' => $desc);
        $this->db->where('id', $id);
        $this->db->update('media', $data);
        echo('done');

    }

    public function delete()
    {
        $id = $this->uri->segment(3);
        $data = array('id' => $id);
        $this->db->delete('media', $data);
        echo("done");
    }

    private function getMedia($id)
    {
        $query = $this->db->query("select id,title,description,path,paththumb,path100,path400,path800,path1024 from media where id=" . $id);
        if ($query->num_rows() > 0) {
            $r = $query->result();
            return $r[0];

        }
        return null;
    }

    private function getTody()
    {
        $this->load->helper('date');
        $now = now();
        date_default_timezone_set('Asia/Katmandu');
        $gmt = local_to_gmt($now);
        $datestring = "%Y-%m-%d";
        return mdate($datestring, $now);
        return $this->getnow();
    }

    public function ttody()
    {
        echo("date:" . $this->getTody());
    }

    public function ti()
    {

        $url = 'http://farm3.static.flickr.com/2591/5727180814_c89b859430_b.jpg';
        $this->doimport($url, 'my import');
        echo("done");
    }

    public function importurl()
    {
        $url = $_POST['url'];
        $title = $_POST['title'];
        $row = $this->doimport($url, $title);
        $data['row'] = $row;
        $this->load->view('mediaitem', $data);
    }

    private function doimport($url, $title)
    {
        define ("FILEREPOSITORY", $this->config->item('userdir'));

        if (!is_dir(FILEREPOSITORY)) {
            mkdir(FILEREPOSITORY);
        }
        $today = $this->getTody();
        if (!is_dir(FILEREPOSITORY . $today)) {
            mkdir(FILEREPOSITORY . $today);
        }
        $name = basename($url);
        if ($title != '') $name = $title;
        $path = FILEREPOSITORY . $today . "/" . "$name";
        copy($url, $path);
        $folder = FILEREPOSITORY . $today;
        return $this->crunchandsave($folder, $path, $name);
    }

    public function upload()
    {
        $userid = $this->checklogin();
        if ($userid > 0) {

            $data = array();
            if (isset($_GET['err'])) {
                $data['err'] = $_GET['err'];
            }
            if (isset($_GET['info'])) {
                $data['err'] = $_GET['info'];
            }
            $this->load->view('media_upload', $data);

        }
    }


    public function doupload()
    {

        define ("FILEREPOSITORY", $this->config->item('userdir'));

        if (isset($_FILES['Filedata'])) {

            if (is_uploaded_file($_FILES['Filedata']['tmp_name'])) {


                if (!is_dir(FILEREPOSITORY)) {
                    mkdir(FILEREPOSITORY);
                }
                $today = $this->getTody();
                if (!is_dir(FILEREPOSITORY . $today)) {
                    mkdir(FILEREPOSITORY . $today);
                }

                $name = $_FILES['Filedata']['name'];
                $path = FILEREPOSITORY . $today . "/" . "$name";
                $result = move_uploaded_file($_FILES['Filedata']['tmp_name'], $path);


                if ($result == 1) {
                    $folder = FILEREPOSITORY . $today;
                    $this->crunchandsave($folder, $path, $name);
                    $info = "File successfully uploaded.";

                    redirect('/index.php/media/upload?info=' . $info, 'refresh');

                } else {
                    $err = "There was a problem uploading the image.";
                    redirect('/index.php/media/upload?err=' . $err, 'refresh');
                }
            }
        } else {
            echo('no found');

        }
        exit(0);
    }

    public function douploadajax()
    {

        define ("FILEREPOSITORY", $this->config->item('userdir'));

        if (isset($_FILES['files'])) {
            $upload = $_FILES['files'];
            $file_name = isset($_SERVER['HTTP_CONTENT_DISPOSITION']) ?
                rawurldecode(preg_replace(
                    '/(^[^"]+")|("$)/',
                    '',
                    $_SERVER['HTTP_CONTENT_DISPOSITION']
                )) : null;

            $tmpname = $_FILES['files']['tmp_name'][0];
            $name = $_FILES['files']['name'][0];
            if (is_uploaded_file($tmpname)) {


                if (!is_dir(FILEREPOSITORY)) {
                    mkdir(FILEREPOSITORY);
                }
                $today = $this->getTody();
                if (!is_dir(FILEREPOSITORY . $today)) {
                    mkdir(FILEREPOSITORY . $today);
                }

                $path = FILEREPOSITORY . $today . "/" . "$name";
                $result = move_uploaded_file($tmpname, $path);
                if ($result == 1) {

                    $folder = FILEREPOSITORY . $today;
                    $media = $this->crunchandsave($folder, $path, $name);
                    //set the data for the json array
                    $file = new stdClass();

                    $file->name = $name;
                    $file->size = $this->get_file_size($path, false);
                    $file->type = 'image/jpeg';

                    $file->url = base_url() . 'media/show/' . $media->id;
                    $file->thumbnail_url = base_url() . 'media/showthumb/' . $media->id; //I set this to original file since I did not create thumbs.  change to thumbnail directory if you do = $upload_path_url .'/thumbs' .$data['file_name']
                    $file->delete_url = base_url() . 'media/delete/' . $media->id;
                    $file->delete_type = 'DELETE';

                    $files = array();
                    $files[0] = $file;

                    echo json_encode(array('files' => $files));
                } else {

                    $file = new stdClass();

                    $file->name = $name;
                    $err = "There was a problem uploading the image.";
                    $file->error = $err;
                    $files = array();
                    $files[0] = $file;

                    echo json_encode(array('files' => $files));
                }
            } else {
                $file = new stdClass();

                $file->name = $name;
                //$err = "There was a problem uploading the image.";
                $err = $upload['error'][0];
                $file->error = $this->getError($err);
                $files = array();
                $files[0] = $file;

                echo json_encode(array('files' => $files));

            }
        } else {
            echo('no found');

        }
        exit(0);
    }

    protected function getError($error)
    {
        if ($error) {
            return $this->get_error_message($error);
        }
        return 'Unknown error.';
    }

    protected function get_error_message($error)
    {
        return array_key_exists($error, $this->error_messages) ?
            $this->error_messages[$error] : $error;
    }

    protected $error_messages = array(
        1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini',
        2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
        3 => 'The uploaded file was only partially uploaded',
        4 => 'No file was uploaded',
        6 => 'Missing a temporary folder',
        7 => 'Failed to write file to disk',
        8 => 'A PHP extension stopped the file upload',
        'post_max_size' => 'The uploaded file exceeds the post_max_size directive in php.ini',
        'max_file_size' => 'File is too big',
        'min_file_size' => 'File is too small',
        'accept_file_types' => 'Filetype not allowed',
        'max_number_of_files' => 'Maximum number of files exceeded',
        'max_width' => 'Image exceeds maximum width',
        'min_width' => 'Image requires a minimum width',
        'max_height' => 'Image exceeds maximum height',
        'min_height' => 'Image requires a minimum height'
    );

    function gs()
    {

    }

    protected function get_file_size($file_path, $clear_stat_cache = false)
    {
        if ($clear_stat_cache) {
            clearstatcache(true, $file_path);
        }
        return $this->fix_integer_overflow(filesize($file_path));

    }

    protected function fix_integer_overflow($size)
    {
        if ($size < 0) {
            $size += 2.0 * (PHP_INT_MAX + 1);
        }
        return $size;
    }

    private function crunchandsave($folder, $path, $name)
    {
        $userid = $this->checklogin();
        $this->load->library('image_lib');
        list($width, $height, $type, $attr) = getimagesize($path);
        $paththumb = null;
        $path100 = null;
        $path400 = null;
        $path800 = null;
        $path1024 = null;
        if ($width > 50) {
            $this->resize($folder, $path, 50, 50, "_thumb", $name);
            $paththumb = $folder . "/_thumb/" . $name;
        }
        if ($width > 100) {
            $this->resize($folder, $path, 100, 100, "_100", $name);
            $path100 = $folder . "/_100/" . $name;
        }
        if ($width > 400) {
            $this->resize($folder, $path, 400, 400, "_400", $name);
            $path400 = $folder . "/_400/" . $name;
        }
        if ($width > 800) {
            $this->resize($folder, $path, 800, 800, "_800", $name);
            $path800 = $folder . "/_800/" . $name;
        }
        if ($width > 1024) {
            $this->resize($folder, $path, 1024, 1024, "_1024", $name);
            $path1024 = $folder . "/_1024/" . $name;
        }
        $title = $name;
        $data = array('title' => $title, 'path' => $path, 'paththumb' => $paththumb, 'path100' => $path100, 'path400' => $path400, 'path800' => $path800, 'path1024' => $path1024);
        $data['userid'] = $userid;

        $this->db->insert('media', $data);
        $id = $this->db->insert_id();
        return $this->getMedia($id);
    }

    private function resize($folder, $path, $width, $height, $suffix, $name)
    {
        $thumb = $suffix;
        if (!is_dir($folder . "/" . $thumb)) {
            mkdir($folder . "/" . $thumb);
        }
        $config['new_image'] = $folder . "/" . $thumb . "/" . $name;
        $config['image_library'] = 'gd2';
        $config['source_image'] = $path;
        $config['maintain_ratio'] = TRUE;
        $config['width'] = $width;
        $config['height'] = $height;
        $config['master_dim'] = 'width';
        $config['thumb_marker'] = $suffix;
        $this->image_lib->clear();
        $this->image_lib->initialize($config);
        $this->image_lib->resize();
    }


}

?>
 

The function douploadajax takes care of files posted by jquery. In addition to the file saving on the server direcotry it crunches files to different sizes and saves the entry to the database table media. Obviously you can makes changes to suit your needs. 


Like us

See also

CRUDL tasks on codeigniter

Complete tutorial on how to create simple CRUDL forms and action handlers on codeigniter.

Codeigniter: MongoDB

- SETUP MONGODB ON CODEGINITER PROJECT - EFFECIENT PAGING METHOD ON MONGODB WITH CODEIGNITER.