Ajax file upload using jQuery and CodeIgniter

Good afternoon!

For a long time on the Internet, I was looking for information on the implementation of AJAX file downloads for CodeIgniter. Different developers offered different technologies and implementation examples. I tried all of them, but not one of them was simple enough and functional at the same time. Only recently I discovered jQuery File Uploader . “He is no different from the rest” - you say, but this is not so. Its main difference is simplicity and good documentation with examples. In the documentation, all callbacks are parsed, all options are described. Implementation in any system does not take much time.

Today I will show how it is very easy to organize multipart uploading files to the server + drug & drop in CodeIgniter.


jQuery File Uploader + CodeIgniter

Out of the box, CodeIgniter offers us to use the library $ this-> load-> library ('upload'); , which allows you to control the transferred files, limiting the download by type, size, width and height of the image. Using it is easy and convenient, but it should be noted a slight restriction imposed on INPUT by this library. The INPUT field must have the parameter name = “userfile” . We agree with this fact and switch to the Controller function that will call the Upload library and, in fact, save our files to disk.

An example implementation of a PHP function:
public function upload(){
		$config['upload_path'] = "/application/uploads/";
		$config['allowed_types'] = "jpg|jpeg|png|gif|flv|mp4|wmv|doc|docx|xsl|xslx|ppt|pptx|zip|rar|tar";
		$config['max_size']	= 2048;
		$config['max_width'] = 800;
		$config['max_height'] = 600;
		$config['encrypt_name'] = TRUE;
		$this->load->library('upload', $config);
		if ($this->upload->do_upload() == false) {
			$error = array('error' => $this->upload->display_errors());
			echo json_encode($error);
		}else{
			$data = $this->upload->data();
			echo json_encode($data);
		}
	}


Attention! In order for all allowed_types to work for you, you need to add the missing MIME-Types to the /application/config/mimes.php configuration file .

We have a function ready to save the file to the server. We pass to the client side. We will need to download from Github jQuery File Upload . The plugin provides great features, but we will not use all of them, we will use only the download of several files, drug & drop and progressall.

We connect the necessary JS to the download page:
 - jquery.fileupload.js
 - jquery.fileupload-video.js
 - jquery.fileupload-process.js
 - jquery.iframe-transport.js
 - upload.js //В комплекте не идет - напишем сами


And CSS file:
 - css/jquery.fileupload.css


Add our INPUT to the page:
 'fileupload')); ?>
			Добавить файл


There is not much left - write upload.js, which will listen to the event of changing the INPUT field and cause the selected file to load. “And where is the promised Drug & Drop?” You ask. Drug & Drop is already running thanks to jQuery File Upload. Instead of calling the standard file selection dialog, you can drag several files onto the page at once and they will be uploaded to the server in order of priority.

And lastly Upload.js
$(document).ready(function(){
    $('#fileupload').fileupload({
    dataType: 'json',
    progressall: function (e, data) {
        var progress = parseInt(data.loaded / data.total * 100, 10);
        $('.progress .bar').css('width', progress + '%'); },
    done: function (e, data) {
        if(data.result.error != undefined){
        $('#error').html(data.result.error); // выводим на страницу сообщение об ошибке если оно есть        
        $('#error').fadeIn('slow');
        }else{
             $('#error').hide(); //на случай если сообщение об ошибке уже отображалось
             $('#files').append("");
                $('#success').fadeIn('slow');
            }
        }
    }
});  
});


data is our response from the server, but it is not an array with information about the downloaded file. All information in JSON format is stored in Data.Result. By the way, console.log (data) will help you find a lot of interesting things, such as: the number of files sent, errors and much more.

That's all, I hope for the usefulness of the material.

Also popular now: