Codeigniter Tutorial - Upload Image File Using Jquery Ajax

Introduction

I will show yous an instance on Ajax file upload using Codeigniter jQuerywithout page refresh. This file upload tutorial example is very helpful to implement the upload functionality. In this example the file is selected using the browse button and file is uploaded to the uploads directory. Codeigniter controller stores the file into the specified location and returns response as a success or failure bulletin from the controller. As a validation stride I have checked if stop users have selected a file for uploading or not.

Related Posts:

  • AJAX Multiple Files Upload using PHP, jQuery
  • AJAX File Upload using PHP, jQuery
  • AJAX Multiple Files Upload using Codeigniter

Prerequisites

PHP seven.3.v
Apache HTTP Server 2.iv
Codeigniter 3.ane.x, jQuery

Example with Source Lawmaking

Creating Project Directory

A typical directory structure for the projection Ajax file upload using Codeigniter jQuery would exist past creating a project directory called codeigniter-three.1.10-jquery-ajax-file-upload.

Nosotros will create some other directory called uploads directory under projection directory which will comprise all uploaded files.

Nosotros may non mention the projection root directory in subsequent sections but we will assume that we are creating file or binder with respect to the projection root directory.

Configuring Auto-load

At present modify awarding/config/autoload.php file for auto-loading html, url, file, form.

This is one time activeness and once you load y'all tin can use uniformly throughout the application code.

          $autoload['helper'] = array('html', 'url', 'file', 'form');        

Creating Controller Form

Create a controller file AjaxFileUpload.php nether application/controllers binder with the following source lawmaking.

This controller class is responsible for handling asking and response of clients and whatsoever validation or business organisation logic as applicable.

          <?php  if (!defined('BASEPATH'))     leave('No direct script access allowed');  /**  * Description of AjaxFileUpload  *  * @writer https://roytuts.com  */ class AjaxFileUpload extends CI_Controller {      role __construct() {         parent::__construct();     }      office alphabetize() {         $this->load->view('file_upload_ajax', Zippo);     }      function upload_file() {          //upload file         $config['upload_path'] = 'uploads/';         $config['allowed_types'] = '*';         $config['max_filename'] = '255';         $config['encrypt_name'] = Truthful;         $config['max_size'] = '1024'; //ane MB          if (isset($_FILES['file']['name'])) {             if (0 < $_FILES['file']['fault']) {                 echo 'Error during file upload' . $_FILES['file']['error'];             } else {                 if (file_exists('uploads/' . $_FILES['file']['proper noun'])) {                     echo 'File already exists : uploads/' . $_FILES['file']['proper name'];                 } else {                     $this->load->library('upload', $config);                     if (!$this->upload->do_upload('file')) {                         echo $this->upload->display_errors();                     } else {                         repeat 'File successfully uploaded : uploads/' . $_FILES['file']['name'];                     }                 }             }         } else {             echo 'Delight choose a file';         }     }  }        

Creating View

Create a view file file_upload_ajax.php under awarding/views directory. Here we have shown how to use ajax file upload using codeigniter jquery.

This file is responsible for giving user options to select and upload file.

The below view file has ane input button for file blazon and some other button for submission once the file is selected for uploading.

Then nosotros grab the button'southward onClick event through jQuery and upload the file at appropriate destination in the server location.

Finally nosotros display either success or failure message as we receive from the server through success or fault methods respectively.

          <!DOCTYPE html> <html>     <head>         <meta charset="UTF-eight">         <title>AJAX File upload using Codeigniter, jQuery</title>         <script blazon="text/javascript" src="https://code.jquery.com/jquery-3.four.1.min.js"></script>         <script type="text/javascript">             $(document).gear up(role (e) {                 $('#upload').on('click', function () {                     var file_data = $('#file').prop('files')[0];                     var form_data = new FormData();                     form_data.append('file', file_data);                     $.ajax({                         url: 'http://localhost/codeigniter-3.i.10-jquery-ajax-file-upload/index.php/ajaxfileupload/upload_file', // point to server-side controller method                         dataType: 'text', // what to expect back from the server                         cache: false,                         contentType: false,                         processData: false,                         data: form_data,                         type: 'post',                         success: role (response) {                             $('#msg').html(response); // brandish success response from the server                         },                         error: function (response) {                             $('#msg').html(response); // display error response from the server                         }                     });                 });             });         </script>     </head>     <body>         <p id="msg"></p>         <input type="file" id="file" name="file" />         <push button id="upload">Upload</button>     </trunk> </html>        

Configuring Route

Modify file application/config/routes.php file because nosotros want our above controller class to be default to load the view file for uploading file.

          $route['default_controller'] = 'ajaxfileupload';        

Testing the Application

If everything is fine then run the awarding by hitting the URL
http://localhost/codeigniter-three.1.10-jquery-ajax-file-upload/index.php. You will go the output in the browser as shown in the beneath image.

ajax file upload using codeigniter jquery

If you attempt to upload file without selecting any file so y'all would see error bulletin "Please cull a file".

ajax file upload using codeigniter jquery

If the file successfully uploaded then you will see success message "File successfully uploaded : uploads/<some-file-name>".

ajax file upload using codeigniter jquery

If the file you are trying to upload already exists and then you will see a message "File already exists : uploads/<some-file-name>".

Hope you have got an idea on ajax file upload file using Codeigniter jQuery.

Source Code

download source code

Thanks for reading.

lancasteryoughlythers.blogspot.com

Source: https://roytuts.com/ajax-file-upload-using-codeigniter-jquery/

0 Response to "Codeigniter Tutorial - Upload Image File Using Jquery Ajax"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel