⚠ In case you've missed it, we have migrated to our new website, with a brand new forum. For more details about the migration you can read our blog post for website migration. This is an archived forum. ⚠

  •     

profile picture

updated [30/07/2013] multiple uploading



victor
  • profile picture
  • Member

Posted 30 July 2013 - 19:52 PM

This is my 3-th topic for our community!  

Hello! I have not had any time for this forum. I was very busy, and I'm busy now too...

So,  I've made an example of multi-uploading because of a lot of people ask about it.

I didn't want to show this example before because of the example is difficult for newbies of GC and PHP and there will too much questions. 

This is result of my work:

[attachment=631:svc.jpg]

NOTE: The example can contain any errors. But I won't change that because it's only example!!!

Are you ready?

Ok! Look at this code:

 

Database scheme












CREATE TABLE IF NOT EXISTS `files` (
  `file_id` int(11) NOT NULL AUTO_INCREMENT,
  `file_name` text NOT NULL,
  `gallery_id` int(11) NOT NULL,
  PRIMARY KEY (`file_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 ;



CREATE TABLE IF NOT EXISTS `gallery` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8  ;

PHP code:












<?php

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

class Uploade extends CI_Controller {

    function __construct()
    {
        parent::__construct();
        $this->load->library('grocery_CRUD');
        $this->load->helper('url');
        $this->config->load('grocery_crud');
    }

    protected $path_to_uploade_function = 'uploade/multi_uploade'; // path to function. you should change the path .("uploade" in this path is a CLASS' NAME)
    private $files = array();
    protected $default_css_path = 'assets/css';
    protected $default_javascript_path = 'assets/js';
    protected $path_to_dirrectory = 'assets/uploads/files/';
    // table description
    protected $file_table = 'files';
    protected $category_id_field = 'gallery_id';
    protected $file_name_field = 'file_name';
    protected $primary_key = 'file_id';

    function gallery()
    {
        $crud = new grocery_CRUD();
        $crud->set_table('gallery');
        $crud->add_fields(array('title', 'photo'));
        $crud->callback_add_field('photo', array($this, 'add_upload_fied'));
        $crud->callback_edit_field('photo', array($this, 'edit_upload_fied'));
        $crud->callback_before_insert(array($this, '_set_files'));
        $crud->callback_after_insert(array($this, '_save_files_into_db'));
        $crud->callback_before_update(array($this, '_set_files'));
        $crud->callback_after_update(array($this, '_save_files_into_db'));
        // if you have no any upload fields on the page you should to set list of the JS files
        $this->_set_js($crud);

        $output = $crud->render();
        $this->_example_output($output);
    }

    function _set_js($crud)
    {
        $crud->set_css('assets/grocery_crud/css/ui/simple/' . grocery_CRUD::JQUERY_UI_CSS);
        $crud->set_css('assets/grocery_crud/css/jquery_plugins/file_upload/file-uploader.css');
        $crud->set_css('assets/grocery_crud/css/jquery_plugins/file_upload/jquery.fileupload-ui.css');
        $crud->set_js('assets/grocery_crud/js/' . grocery_CRUD::JQUERY);
        $crud->set_js('assets/grocery_crud/js/jquery_plugins/ui/' . grocery_CRUD::JQUERY_UI_JS);
        $crud->set_js('assets/grocery_crud/js/jquery_plugins/tmpl.min.js');
        $crud->set_js('assets/grocery_crud/js/jquery_plugins/load-image.min.js');
        $crud->set_js('assets/grocery_crud/js/jquery_plugins/jquery.iframe-transport.js');
        $crud->set_js('assets/grocery_crud/js/jquery_plugins/jquery.fileupload.js');
        $crud->set_js('assets/grocery_crud/js/jquery_plugins/config/jquery.fileupload.config.js');
        $crud->set_css('assets/grocery_crud/css/jquery_plugins/fancybox/jquery.fancybox.css');
        $crud->set_js('assets/grocery_crud/js/jquery_plugins/jquery.fancybox.pack.js');
        $crud->set_js('assets/grocery_crud/js/jquery_plugins/jquery.easing-1.3.pack.js');
        $crud->set_js('assets/grocery_crud/js/jquery_plugins/jquery.mousewheel-3.0.4.pack.js');
        $crud->set_js('assets/grocery_crud/js/jquery_plugins/config/jquery.fancybox.config.js');
    }

    function add_upload_fied()
    {
        $html = '
<div>
<span class="fileinput-button qq-upload-button" id="upload-button-svc">
<span>Upload a file</span>
<input type="file" name="multi_aploade" id="multi_aploade_field" >
</span> <span class="qq-upload-spinner" id="ajax-loader-file" style="display:none;"></span>
<span id="progress-multiple" style="display:none;"></span>
</div>
<select name="files[]" multiple="multiple" size="8" class="multiselect" id="file_multiple_select" style="display:none;">
</select>
<div id="file_list_svc" style="margin-top: 40px;">
</div>';
        $html.=$this->JS();
        return $html;
    }

    function edit_upload_fied($value, $primary_key)
    {
        $files = $this->db->get_where($this->file_table, array($this->category_id_field => $primary_key))->result_array();
        $html = '
<div>
<span class="fileinput-button qq-upload-button" id="upload-button-svc">
<span>Upload a file</span>
<input type="file" name="multi_aploade" id="multi_aploade_field" >
</span> <span class="qq-upload-spinner" id="ajax-loader-file" style="display:none;"></span>
<span id="progress-multiple" style="display:none;"></span>
</div>';

        $html.= '<select name="files[]" multiple="multiple" size="8" class="multiselect" id="file_multiple_select" style="display:none;">';
        if (!empty($files))
        {
            foreach ($files as $items)
            {
                $html.="<option value=" . $items['file_name'] . " selected='selected'>" . $items['file_name'] . "</option>";
            }
        }
        $html.='</select>';
        $html.='<div id="file_list_svc" style="margin-top: 40px;">';
        if (!empty($files))
        {
            foreach ($files as $items)
            {
                if ($this->_is_image($items['file_name']) === true)
                {
                    $html.= '<div id="' . $items['file_name'] . '">';
                    $html.= '<a href="' . base_url() . $this->path_to_dirrectory . $items['file_name'] . '" class="image-thumbnail" id="fancy_' . $items['file_name'] . '">';
                    $html.='<img src="' . base_url() . $this->path_to_dirrectory . $items['file_name'] . '" height="50"/>';
                    $html.='</a>';
                    $html.='<a href="javascript:" onclick="delete_file_svc(this,'' . $items['file_name'] . '')" style="color:red;" >Delete</a>';
                    $html.='</div>';
                }
                else
                {
                    $html.='<div id="' . $items['file_name'] . '" >
                          <span>' . $items['file_name'] . '</span> 
                          <a href="javascript:" onclick="delete_file_svc(this,'' . $items['file_name'] . '')" style="color:red;" >Delete</a>
                          </div>';
                }
            }
        }
        $html.='</div>';
        $html.=$this->JS();
        return $html;
    }

    function _is_image($name)
    {
        return ((substr($name, -4) == '.jpg')
                || (substr($name, -4) == '.png')
                || (substr($name, -5) == '.jpeg')
                || (substr($name, -4) == '.gif' )
                || (substr($name, -5) == '.tiff')) ? true : false;
    }

    function JS()
    {
        $js = "<script>
function delete_file_svc(link,filename)
{
$('#file_multiple_select option[value=\"'+filename+'\"]').remove();
$(link).parent().remove();
    $.post('" . base_url() . $this->path_to_uploade_function . "/delete_file', 'file_name='+filename, function(json){
        if(json.succes == 'true')
        {
            console.log('json data', json);
        }
    }, 'json');   
}
$(document).ready(function() {
    $('#multi_aploade_field').fileupload({
         url: '" . base_url() . $this->path_to_uploade_function . "/uploade',
         sequentialUploads: true,
         cache: false,
          autoUpload: true,
          dataType: 'json',
          acceptFileTypes: /(\.|\/)(" . $this->config->item('grocery_crud_file_upload_allow_file_types') . ")$/i,
          limitMultiFileUploads: 1,
          beforeSend: function()
          {
          $('#upload-button-svc').slideUp('fast');
          $('#ajax-loader-file').css('display','block');
           $('#progress-multiple').css('display','block');
          },
          progress: function (e, data) {
        $('#progress-multiple').html(string_progress + parseInt(data.loaded / data.total * 100, 10) + '%');
        },
          done: function (e, data)
          {
           console.log(data.result);
           $('#file_multiple_select').append('<option value=\"'+data.result.file_name+'\" selected=\"selected\">'+data.result.file_name+'</select>');
           var is_image = (data.result.file_name.substr(-4) == '.jpg'  
                                        || data.result.file_name.substr(-4) == '.png' 
                                        || data.result.file_name.substr(-5) == '.jpeg' 
                                        || data.result.file_name.substr(-4) == '.gif' 
                                        || data.result.file_name.substr(-5) == '.tiff')
                                                ? true : false;
         var html;
         if(is_image==true)
         {
         html='<div id=\"'+data.result.file_name+'\" ><a href=\"" . base_url() . $this->path_to_dirrectory . "'+data.result.file_name+'\" class=\"image-thumbnail\" id=\"fancy_'+data.result.file_name+'\">';
         html+='<img src=\"" . base_url() . $this->path_to_dirrectory . "'+data.result.file_name+'\" height=\"50\"/>';
         html+='</a><a href=\"javascript:\" onclick=\"delete_file_svc(this,''+data.result.file_name+'')\" style=\"color:red;\" >Delete</a><div>';
        $('#file_list_svc').append(html);
$('.image-thumbnail').fancybox({
        'transitionIn'	:	'elastic',
        'transitionOut'	:	'elastic',
        'speedIn'		:	600, 
        'speedOut'		:	200, 
        'overlayShow'	:	true
});
         }
         else
         {
          html = '<div id=\"'+data.result.file_name+'\" ><span>'+data.result.file_name+'</span> <a href=\"javascript:\" onclick=\"delete_file_svc(this,''+data.result.file_name+'')\" style=\"color:red;\" >Delete</a><div>';
         $('#file_list_svc').append(html);
}
          $('#upload-button-svc').show('fast');
          $('#ajax-loader-file').css('display','none');
          $('#progress-multiple').css('display','none');
          $('#progress-multiple').html('');
          }
     });

});
</script>";
        return $js;
    }

    function multi_uploade($action = NULL)
    {
        switch ($action)
        {
            case 'uploade':
                $this->uploade_file();

                break;
            case 'delete_file':
                $this->delete_file();

                break;

            default:

                break;
        }
    }

    function uploade_file()
    {
        $json = NULL;
        $config['upload_path'] = $this->path_to_dirrectory;
        $config['allowed_types'] = $this->config->item('grocery_crud_file_upload_allow_file_types');
        $config['encrypt_name'] = TRUE;
        $config['remove_spaces'] = TRUE;
        $config['max_filename'] = 0;
        $this->load->library('upload', $config);
        if (!$this->upload->do_upload('multi_aploade'))
        {
            $json['error'] = $this->upload->display_errors();
            $json['success'] = 'false';
        }
        else
        {
            $uploade_data = $this->upload->data();
            $json['success'] = 'true';
            $json['file_name'] = $uploade_data['file_name'];
        }
        echo json_encode($json);
        exit;
    }

    function _set_files($post_array)
    {
        $this->files = $post_array['files'];
        unset($post_array['files']);
        return $post_array;
    }

    function _save_files_into_db($post_array, $primary_key)
    {
        $this->db->delete($this->file_table, array($this->category_id_field => $primary_key));
        $files = array();
        if (!empty($this->files))
        {
            foreach ($this->files as $file)
            {
                $files[] = array($this->category_id_field => $primary_key, 'file_name' => $file);
            }
        }
        if (!empty($files))
        {
            $this->db->insert_batch($this->file_table, $files);
        }
        return true;
    }

    function delete_file($file_name = NULL)
    {
        $file_name = $this->input->post('file_name') ? $this->input->post('file_name') : $file_name;
        $this->db->delete($this->file_table, array($this->file_name_field => $file_name));
        if (file_exists($this->path_to_dirrectory . $file_name))
        {
            unlink($this->path_to_dirrectory . $file_name);
        }
        $json = array('success' => true);
        echo json_encode($json);
        exit;
    }

    function _example_output($output = null)
    {
        $this->load->view('example', $output);
    }

}

and then you should change JS code,

1) open this: 

assets/grocery_crud/themes/flesxigrid/js/flexigrid-add.js

2) change a function called clearForm like i typed bellow
 











	function clearForm()
	{
		$('#crudForm').find(':input').each(function() {
	        switch(this.type) {
	            case 'password':
	            case 'select-multiple':
	            case 'select-one':
	            case 'text':
	            case 'textarea':
	                $(this).val('');
	                break;
	            case 'checkbox':
	            case 'radio':
	                this.checked = false;
	        }
	    });

		/* Clear upload inputs  */
		$('.open-file,.gc-file-upload,.hidden-upload-input').each(function(){
			$(this).val('');
		});
		
		$('.upload-success-url').hide();
		$('.fileinput-button').fadeIn("normal");
		/* -------------------- */		
		
		$('.remove-all').each(function(){
			$(this).trigger('click');
		});
		
		$('.chosen-multiple-select, .chosen-select, .ajax-chosen-select').each(function(){
			$(this).trigger("liszt:updated");
		});
                
               $('#file_list_svc').html('');
               $("#file_multiple_select").empty();
	}

As you see, it's only a few string and this functionality will work pretty well  :D

P.S: I'm hungry and angry today

P.S.S: Sorry for my English. I have no time to learn it.

P.S.S.S: I do not sell any fridges
 
 


davidoster
  • profile picture
  • Member

Posted 30 July 2013 - 20:38 PM

Interesting solution! I will have a closer look later! Thanks for sharing [member=victor]!!!

Good luck with the extremely big project you have undertaken!!!

 

P.S. You need to sleep from time to time in order to finish the project  ;)


victor
  • profile picture
  • Member

Posted 30 July 2013 - 20:41 PM

you're right)

Amit Shah
  • profile picture
  • Member

Posted 02 August 2013 - 09:11 AM

Interesting one ... thank you victor for wonderful contribution. This surely should be an awsome help ... i too will like to explore much over it..


victor
  • profile picture
  • Member

Posted 02 August 2013 - 16:56 PM

Ok guys. if you have any errors let me know please. when I'll have more time I'll update this example. As you see there are some properties which you can change and the example will work with your code. I was lasy when I was making the code and I didn't explane how it works. if you're interesting in it you can ask me

victor
  • profile picture
  • Member

Posted 04 August 2013 - 00:22 AM

are there any questions?


victor
  • profile picture
  • Member

Posted 04 August 2013 - 00:27 AM

offtopic: there is an interesting bug in the engine of the forum. When I update a post, a new extra empty string appears in my code.


davidoster
  • profile picture
  • Member

Posted 04 August 2013 - 10:29 AM

offtopic: there is an interesting bug in the engine of the forum. When I update a post, a new extra empty string appears in my code.

 

??? really? hmmm. only on the pasted code. right? it doesn't change the uploaded file: /index.php?app=core&module=attach&section=attach&attach_id=632


victor
  • profile picture
  • Member

Posted 04 August 2013 - 10:33 AM

try to use the code above. I've updated it a bit.


victor
  • profile picture
  • Member

Posted 04 August 2013 - 10:36 AM

yes

 

??? really? hmmm. only on the pasted code. right? it doesn't change the uploaded file: /index.php?app=core&module=attach&section=attach&attach_id=632

yes. The file doesn't changes. only the code which you can see above.


davidoster
  • profile picture
  • Member

Posted 04 August 2013 - 10:39 AM

very interesting...


victor
  • profile picture
  • Member

Posted 04 August 2013 - 10:39 AM

Maybe the bug was because of I forgot to delete extra code (print_r()) from the function. I just deleted the php file. Copy the code from the example


Amit Shah
  • profile picture
  • Member

Posted 29 January 2014 - 08:21 AM

Hello Victor,

 

Its really a very nice thing u have shared.. it surely have helped me... but 1 thing that misses out here is .. ability to add tittle to each upload... If we can crack that facility / feature - that will surely be awesome achievement :)


JuanB
  • profile picture
  • Member

Posted 19 April 2014 - 05:11 AM

I tried to use but show me some errors, somebody can share this code please? thanks!


Amit Shah
  • profile picture
  • Member

Posted 19 April 2014 - 06:20 AM

Well you follow it correctly - u dont get error. Its been tested / applied into projects and never faced issues as such. Yes if any mistakes in applying the same - it will surely give errors.


JuanB
  • profile picture
  • Member

Posted 21 April 2014 - 01:08 AM

I added the line: 

 

$this->load->database();

 

and works, but after select the file doesn't load me anything, dont charge anything, some help please?


Peter
  • profile picture
  • Member

Posted 27 July 2014 - 17:42 PM

Sorry to say that its not working for me, please someone share working copy


wisp2k
  • profile picture
  • Member

Posted 09 January 2015 - 15:46 PM

may I ask where I've to insert the php code? I don't understand in which file? I actually navigate the site through the index.php right?


titu
  • profile picture
  • Member

Posted 01 March 2015 - 15:20 PM

Victor, this is magic. Thanks.


victor
  • profile picture
  • Member

Posted 10 March 2015 - 20:22 PM

Victor, this is magic. Thanks.

;)