Tuesday, November 5, 2013

jquery file upload plugin with php method with custom progress bar

var url = window.location.hostname === 'blueimp.github.io' ? '//jquery-file-upload.appspot.com/' : '<?php echo admin_url('media/upload'); ?>';
кодыг сайн анхаар "window.location.hostname" ;

server side php

private function initialize() {
        if ($this->_server_var('REQUEST_METHOD') == 'GET') {
            $seleted_dir_id = $this->session->userdata(self::$SELECTED_DIR_ID);
            if (empty($seleted_dir_id)) {
                $seleted_dir_id = 0;
            }
            if ($seleted_dir_id === TRUE) {
                $seleted_dir_id = 0;
            }
            try {
                $files = $this->media_model->get_list(array('folder_id' => $seleted_dir_id));
                echo json_encode($files);
            } catch (Exception $ex) {
                log_message('error', $ex->getMessage());
            }
        }
    }

    public function upload() {
        $this->initialize();

        $upload = isset($_FILES['files']) ? $_FILES['files'] : null;
        // Parse the Content-Disposition header, if available:
        $file_name = $this->_server_var('HTTP_CONTENT_DISPOSITION') ? rawurldecode(preg_replace('/(^[^"]+")|("$)/', '', $this->_server_var('HTTP_CONTENT_DISPOSITION'))) : null;
        // Parse the Content-Range header, which has the following form:
        // Content-Range: bytes 0-524287/2000000
        $content_range = $this->_server_var('HTTP_CONTENT_RANGE') ? preg_split('/[^0-9]+/', $this->_server_var('HTTP_CONTENT_RANGE')) : null;
        $size = $content_range ? $content_range[3] : null;

        $files = array();
        if ($upload && is_array($upload['tmp_name'])) {
            // param_name is an array identifier like "files[]",
            // $_FILES is a multi-dimensional array:
            foreach ($upload['tmp_name'] as $index => $value) {
                $files[] = $this->_handle_file_upload(
                        $upload['tmp_name'][$index], $file_name ? $file_name : $upload['name'][$index], $size ? $size : $upload['size'][$index], $upload['type'][$index], $upload['error'][$index], $index, $content_range
                );
            }
        } else {

            // param_name is a single object identifier like "file",
            // $_FILES is a one-dimensional array:
            $files[] = $this->_handle_file_upload(
                    isset($upload['tmp_name']) ? $upload['tmp_name'] : null, $file_name ? $file_name : (isset($upload['name']) ? $upload['name'] : null), $size ? $size : (isset($upload['size']) ? $upload['size'] : $this->_server_var('CONTENT_LENGTH')), isset($upload['type']) ? $upload['type'] : $this->_server_var('CONTENT_TYPE'), isset($upload['error']) ? $upload['error'] : null, null, $content_range
            );
        }

        echo json_encode($files);
    }

    // -----------------------------------------------------------------------

    private function _handle_file_upload($uploaded_file, $name, $size, $type, $error, $index = null, $content_range = null) {       
        $file = new stdClass();
        $file->name = $this->_file_name($name, $type, $index, $content_range);
        $file->size = $this->_fix_integer_overflow(intval($size));
        $file->type = $type;

        $seleted_dir_id = $this->session->userdata(self::$SELECTED_DIR_ID);
        $seleted_dir_path = $this->session->userdata(self::$SELECTED_DIR_PATH);
        if (!empty($seleted_dir_path)) {
            $seleted_dir_path = $seleted_dir_path . '/';
        }

        $validate = $this->_validate_file($uploaded_file, $file, $error, $index);
       
        if ($seleted_dir_id && $validate) {
            if ($seleted_dir_id === TRUE) {
                $seleted_dir_id = 0;
            }
            //path generate
            $upload_dir = UPLOADPATH . $seleted_dir_path;
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, $this->config->item('mkdir_mode'), true);
            }
            $file_path = $upload_dir . $file->name;
            //check is uploaded file
            $append_file = $content_range && is_file($file_path) && $file->size > $this->_file_size($file_path);
            if ($uploaded_file && is_uploaded_file($uploaded_file)) {
                // multipart/formdata uploads (POST method uploads)
                if ($append_file) {
                    file_put_contents(
                            $file_path, fopen($uploaded_file, 'r'), FILE_APPEND
                    );
                } else {
                    move_uploaded_file($uploaded_file, $file_path);
                }
            } else {
                // Non-multipart uploads (PUT method support)
                file_put_contents(
                        $file_path, fopen('php://input', 'r'), $append_file ? FILE_APPEND : 0
                );
            }
            //check is upload success
            $file_size = $this->_file_size($file_path, $append_file);
            if ($file_size === $file->size) {

                $fext = strtolower(strrchr($file->name, '.'));
                $fname = empty($fext) ? $file->name : stristr($file->name, $fext, true);
                $fret = $this->thumbmanager->get_mimetype_groupname($fext);

                if ($fret === FALSE) {
                    $file->error = 'Зөвшөөрөгдсөн файлын төрөл биш байна!';
                } else {
                    $mimetype = (is_array($fret[1]) ? $fret[1][0] : $fret[1]);

                    $media = array();
                    $media['typecode'] = $fret[0];
                    $media['folder_id'] = $seleted_dir_id;
                    $media['filename'] = $fname;
                    $media['extension'] = substr($fext, 1);
                    $media['mimetype'] = $mimetype;
                    $media['size'] = $file_size;
                    $media['createddate'] = utc_datetime();
                    $media['user_id'] = User()->get_user_id();

                    if ($this->media_model->insert($media) > 0) {
                        $file->url = $this->thumbmanager->thumb_url($media);
                    }
                }
            } else {
                $file->size = $file_size;
                if (!$content_range && $this->config->item('discard_aborted_uploads')) {
                    unlink($file_path);
                    $file->error = 'abort';
                }
            }
        }
        return $file;
    }
 
CSS
 
/*
    Document   : file
    Created on : Nov 5, 2013, 10:12:17 PM
    Author     : boroo
    Description:
        Purpose of the stylesheet follows.
*/
.process {
    display: block;
    position: relative;
    height: 20px;
    width: 100%;
}
.progress-bar {
    background: url(images/progressbar.gif) repeat-x scroll left top #333;
}
.progress-bar-success {
    float: left;
    height: 20px;
    position: relative;
}


.fileinput-button {
  position: relative;
  overflow: hidden;
}

.fileinput-button input {
  position: absolute;
  top: 0;
  right: 0;
  margin: 0;
  opacity: 0;
  -ms-filter: 'alpha(opacity=0)';
  font-size: 200px;
  direction: ltr;
  cursor: pointer;
}

/* Fixes for IE < 8 */
@media screen\9 {
  .fileinput-button input {
    filter: alpha(opacity=0);
    font-size: 100%;
    height: 100%;
  }
}


HTML



<!-- The jQuery UI widget factory, can be omitted if jQuery UI is already included -->
<script src="<?php echo theme_url('jQuery-File-Upload-9.0.1/js/vendor/jquery.ui.widget.js', 'shared'); ?>"></script>
<!-- The Iframe Transport is required for browsers without support for XHR file uploads -->
<script src="<?php echo theme_url('jQuery-File-Upload-9.0.1/js/jquery.iframe-transport.js', 'shared'); ?>"></script>
<!-- The basic File Upload plugin -->
<script src="<?php echo theme_url('jQuery-File-Upload-9.0.1/js/jquery.fileupload.js', 'shared'); ?>"></script>
<script>
    /*jslint unparam: true */
    /*global window, $ */
    $(function() {
        'use strict';
        // Change this to the location of your server-side upload handler:
        var url = window.location.hostname === 'blueimp.github.io' ? '//jquery-file-upload.appspot.com/' : '<?php echo admin_url('media/upload'); ?>';
        $('#fileupload').fileupload({
            url: url,
            dataType: 'json',
            acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
            process: [
                {
                    action: 'load',
                    fileTypes: /^image\/(gif|jpeg|png)$/,
                    maxFileSize: 5000000 // 5MB
                },
                {
                    action: 'resize',
                    maxWidth: 1440,
                    maxHeight: 900
                },
                {
                    action: 'save'
                }
            ],
            done: function(e, data) {
                if (data && typeof data.result !== 'undefined') {
                    try {
                        for (var key in data.result) {
                            var item = data.result[key];
                            $('<img/>').attr('src', '<?php echo site_url(); ?>' + item.url)
                                    .appendTo('#files');
                        }
                    } catch (ex) {
                        alert(ex);
                    }
                }
            },
            error: function(e, data) {
                var a = 1;
            },
            progressall: function(e, data) {
                var progress = parseInt(data.loaded / data.total * 100, 10);
                $('#progress .progress-bar').css('width', progress + '%');
            }
        }).prop('disabled', !$.support.fileInput).parent().addClass($.support.fileInput ? undefined : 'disabled');
    });
</script>