How Can I Upload File in Codeigniter Stackoverflow

File upload is the most used feature in the web application where the files are managed dynamically. The file can exist hands uploaded to the server using PHP. Also, you can upload multiple files at a time using PHP. For the CodeIgniter web application, you tin utilize the system library to implement file upload functionality. CodeIgniter Upload library helps you to upload files to the server in CodeIgniter.

CodeIgniter's File Uploading Class allows files to be uploaded to the server. You tin upload files or images hands using the Upload library in CodeIgniter. Non simply a single file, simply also the multiple files can be uploaded with CodeIgniter Upload library. In this tutorial, we will testify you how to upload multiple files and images at once using CodeIgniter's Upload Library.

In the example lawmaking, the post-obit functionality volition be implemented to upload multiple files in CodeIgniter.

  • Create an HTML form to select image files to upload.
  • Upload multiple images to the server at once using CodeIgniter's Upload library.
  • Store file data in the MySQL database.
  • Retrieve images from the database and display them on the web page.

How to Upload File in CodeIgniter

Create Database Table

To shop the file name and related information, a tabular array is required in the database. The following SQL creates a files table with bones fields in the MySQL database.

          CREATE          Tabular array          `files`          (          `id`          int(11)          Non          NULL          AUTO_INCREMENT,          `file_name`          varchar(255)          COLLATE          utf8_unicode_ci          Non          Goose egg,          `uploaded_on`          datetime          NOT          Nil,          `condition`          enum('1','0')          COLLATE          utf8_unicode_ci          NOT          Zilch          DEFAULT          '1'          Annotate          '1=Active, 0=Inactive',  PRIMARY          Primal          (`id`) )          ENGINE=InnoDB          DEFAULT          CHARSET=utf8          COLLATE=utf8_unicode_ci;

Create File Upload Folder

Create a directory on the server where you want to shop the uploaded files. For instance, create a uploads/files/ directory in the root folder of the CodeIgniter awarding.

codeigniter-multiple-files-upload-tutorial-create-upload-folder-codexworld

Controller (Upload_files.php)

The Upload_Files controller handles the multiple files upload and image brandish functionality.

  • __construct()
    • Loads File model that helps to insert file information into the database and fetch files data from the database.
  • alphabetize()
    • Check if the upload grade is submitted with files.
    • Set preferences (upload path, immune types, etc) and initialize Upload library.
    • Upload images to the server using the Upload library.
    • Insert images data in the database using the insert() method of the File model.
    • Fetch all images from the database using the getRows() method of the File model.
    • Laissez passer image information and upload status to the view.
          <?php            
divers
( 'BASEPATH' ) OR exit( 'No direct script access allowed' );

class

Upload_Files extends CI_Controller {
    function
__construct () {
parent :: __construct (); // Load file model
$this -> load -> model ( 'file' );
    }

         function

index (){
$information = assortment();
$errorUploadType = $statusMsg = '' ; // If file upload form submitted
if( $this -> input -> postal service ( 'fileSubmit' )){ // If files are selected to upload
if(!empty( $_FILES [ 'files' ][ 'name' ]) && count ( array_filter ( $_FILES [ 'files' ][ 'name' ])) > 0 ){
$filesCount = count ( $_FILES [ 'files' ][ 'proper name' ]);
                for(
$i = 0 ; $i < $filesCount ; $i ++){
$_FILES [ 'file' ][ 'name' ]     = $_FILES [ 'files' ][ 'proper noun' ][ $i ];
$_FILES [ 'file' ][ 'type' ]     = $_FILES [ 'files' ][ 'type' ][ $i ];
$_FILES [ 'file' ][ 'tmp_name' ] = $_FILES [ 'files' ][ 'tmp_name' ][ $i ];
$_FILES [ 'file' ][ 'error' ]     = $_FILES [ 'files' ][ 'fault' ][ $i ];
$_FILES [ 'file' ][ 'size' ]     = $_FILES [ 'files' ][ 'size' ][ $i ]; // File upload configuration
$uploadPath = 'uploads/files/' ;
$config [ 'upload_path' ] = $uploadPath ;
$config [ 'allowed_types' ] = 'jpg|jpeg|png|gif' ;
//$config['max_size']    = '100';
                    //$config['max_width'] = '1024';
                    //$config['max_height'] = '768';

                                         // Load and initialize upload library

$this -> load -> library ( 'upload' , $config );
$this -> upload -> initialize ( $config ); // Upload file to server
if( $this -> upload -> do_upload ( 'file' )){
// Uploaded file information
$fileData = $this -> upload -> data ();
$uploadData [ $i ][ 'file_name' ] = $fileData [ 'file_name' ];
$uploadData [ $i ][ 'uploaded_on' ] = date ( "Y-m-d H:i:south" );
                    }else{
$errorUploadType .= $_FILES [ 'file' ][ 'proper name' ]. ' | ' ;
                    }
                }
$errorUploadType = !empty( $errorUploadType )? '<br/>File Type Error: ' . trim ( $errorUploadType , ' | ' ): '' ;
                if(!empty(
$uploadData )){
// Insert files information into the database
$insert = $this -> file -> insert ( $uploadData ); // Upload status message
$statusMsg = $insert ? 'Files uploaded successfully!' . $errorUploadType : 'Some problem occurred, please endeavor again.' ;
                }else{
$statusMsg = "Sorry, there was an error uploading your file." . $errorUploadType ;
                }
            }else{
$statusMsg = 'Please select paradigm files to upload.' ;
            }
        }
// Get files data from the database
$data [ 'files' ] = $this -> file -> getRows (); // Pass the files information to view
$data [ 'statusMsg' ] = $statusMsg ;
$this -> load -> view ( 'upload_files/index' , $data );
    }

}

Model (File.php)

The File model handles the database related operations (fetch and insert).

  • __construct() – Define table name where the files data will be stored.
  • getRows()
    • Fetch the file data from the database.
    • Returns a single tape if the ID is specified, otherwise all records.
  • insert()
    • Insert multiple files information into the database using the insert_batch() office of CodeIgniter Query Architect Class.
          <?php            
defined
( 'BASEPATH' ) OR go out( 'No straight script access immune' );

class

File extends CI_Model {
    function
__construct () {
$this -> tableName = 'files' ;
    }
/*
     * Fetch files data from the database
     * @param id returns a single record if specified, otherwise all records
     */
public function getRows ( $id = '' ){
$this -> db -> select ( 'id,file_name,uploaded_on' );
$this -> db -> from ( 'files' );
        if(
$id ){
$this -> db -> where ( 'id' , $id );
$query = $this -> db -> become ();
$result = $query -> row_array ();
        }else{
$this -> db -> order_by ( 'uploaded_on' , 'desc' );
$query = $this -> db -> get ();
$result = $query -> result_array ();
        }
        return !empty(
$result )? $effect : imitation ;
    }
/*
     * Insert file data into the database
     * @param array the data for inserting into the tabular array
     */
public function insert ( $data = array()){
$insert = $this -> db -> insert_batch ( 'files' , $information );
        return
$insert ? truthful : false ;
    }
}

View (upload_files/index.php)

Initially, an HTML grade is displayed with file input to select multiple files.

  • After the form submission, the data is posted to the alphabetize() part of the Upload_Files controller for uploading multiple images to the server.
  • Based on the upload response, the condition message is displayed on the web page.
            <?php          echo !empty(          $statusMsg          )?          '<p grade="status-msg">'          .          $statusMsg          .          '</p>'          :          ''          ;          ?>                    <form            method="post"            action=""            enctype="multipart/form-data">          <div            class="form-group">          <label>Cull Files</label>          <input            blazon="file"            class="class-control"            name="files[]"            multiple/>          </div>          <div            form="form-group">          <input            course="course-control"            type="submit"            name="fileSubmit"            value="UPLOAD"/>          </div>          </form>        

Under the file upload form,

  • The uploaded file names are fetched from the database.
  • The respective images are retrieved from the server.
  • The images are listed in a gallery view.
            <div            class="row">          <h3>Uploaded Files/Images</h3>          <ul            form="gallery">          <?php          if(!empty(          $files          )){ foreach(          $files          as          $file          ){          ?>          <li            class="particular">          <img            src="<?php              echo              base_url              (              'uploads/files/'              .              $file              [              'file_name'              ]);              ?>"            >          <p>Uploaded On          <?php          echo          date          (          "j Thousand Y"          ,          strtotime          (          $file          [          'uploaded_on'          ]));          ?>          </p>          </li>          <?php          } }else{          ?>          <p>File(s) not found...</p>          <?php          }          ?>          </ul>          </div>        

Upload Class Preferences

In the case, some bones preferences are used to Upload library configuration ($config). But you can specify various preferences provided by the Upload Course in CodeIgniter.

  • upload_path – The path of the directory where the file will exist uploaded. The path must be absolute and directory must be writable.
  • allowed_types – The mime types of the file that allows being uploaded.
  • file_name – If specified, the uploaded file will be renamed with this name.
  • file_ext_tolower – (TRUE/FALSE) If set to Truthful, file extension will be lower case.
  • overwrite – (Truthful/Imitation) True – If a file exists with the same proper noun, it volition exist overwritten. FALSE – If a file exists with the aforementioned name, a number will append to the filename.
  • max_size – (in kilobytes) The maximum size of the file that allowed to upload. Set to 0 for no limit.
  • max_width – (in pixels) The maximum width of the epitome that immune to upload. Prepare to 0 for no limit.
  • max_height – (in pixels) The maximum height of the image that allowed to upload. Set up to 0 for no limit.
  • min_width – (in pixels) The minimum width of the image that allowed to upload. Ready to 0 for no limit.
  • min_height – (in pixels) The minimum height of the epitome that immune to upload. Set to 0 for no limit.
  • max_filename – The maximum length of the file proper noun. Set to 0 for no limit.

Multiple Image Upload with View, Edit and Delete in CodeIgniter

Are you want to become implementation help, or alter or heighten the functionality of this script? Submit Paid Service Request

If you lot have whatsoever questions nigh this script, submit it to our QA community - Ask Question

tiltonderto1984.blogspot.com

Source: https://www.codexworld.com/codeigniter-upload-multiple-files-images/

Related Posts

0 Response to "How Can I Upload File in Codeigniter Stackoverflow"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel