Codeigniter no refresh upload in the implementation of the code

  • 2021-12-05 05:46:36
  • OfStack

I haven't updated it for a long time. Write it as a translation. Pure originality is not available. XD

Codeigniter is still very easy to use, and freshwater 1 straight is highly respected. Upload without refresh in codeigniter, and upload with AJAX technology in fashion 1. Jquery and AjaxFileUpload are used.

Build a table first


CREATE TABLE `files` (
 `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
 `filename` VARCHAR(255) NOT NULL,
 `title` VARCHAR(100) NOT NULL
);

The directory structure of the file is as follows:


public_html/
- application/
 - - controllers/
 -  upload.php
 - - models/
 -  files_model.php
 - - views/
 -  upload.php
 -  files.php
- css/
 - - style.css
- files/
- js/
 - - AjaxFileUpload.js
 - - site.js

Step 1: Create a form

It looks like an title text field, a file box, a submit button, and an div for files.

Controller part

First, we want to build an uploaded form and an Controller of upload. Expose the view of upload in index method. As follows:


class Upload extends CI_Controller
{
  public function __construct()
  {
   parent::__construct();
   $this->load->model('files_model');
   $this->load->database();
   $this->load->helper('url');
  }
 
  public function index()
  {
   $this->load->view('upload');
  }
}

We have already loaded files_model in the construct, so we can use the method in files_model.

Create a form view

The view file upload. php contains our upload form.


<!doctype html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
  <script src="<?php echo base_url()?>js/site.js"></script>
  <script src="<?php echo base_url()?>js/ajaxfileupload.js"></script>
  <link href="<?php echo base_url()?>css/style.css" rel="external nofollow" rel="stylesheet" />
</head>
<body>
  <h1>Upload File</h1>
  <form method="post" action="" id="upload_file">
   <label for="title">Title</label>
   <input type="text" name="title" id="title" value="" />
 
   <label for="userfile">File</label>
   <input type="file" name="userfile" id="userfile" size="20" />
 
   <input type="submit" name="submit" id="submit" />
  </form>
  <h2>Files</h2>
  <div id="files"></div>
</body>
</html>

We loaded the jquery, ajaxfileupload and our own site. js files at the beginning of the file. Id for files div is used by us to display the list of uploaded files.

1 Some simple css

Establishment of style. css under css


h1, h2 { font-family: Arial, sans-serif; font-size: 25px; }
h2 { font-size: 20px; }
 
label { font-family: Verdana, sans-serif; font-size: 12px; display: block; }
input { padding: 3px 5px; width: 250px; margin: 0 0 10px; }
input[type="file"] { padding-left: 0; }
input[type="submit"] { width: auto; }
 
#files { font-family: Verdana, sans-serif; font-size: 11px; }
#files strong { font-size: 13px; }
#files a { float: right; margin: 0 0 5px 10px; }
#files ul { list-style: none; padding-left: 0; }
#files li { width: 280px; font-size: 12px; padding: 5px 0; border-bottom: 1px solid #CCC; }

Step 2, Javascript

Establishing site. js under js


$(function() {
  $('#upload_file').submit(function(e) {
   e.preventDefault();
   $.ajaxFileUpload({
     url     :'./upload/upload_file/',
     secureuri   :false,
     fileElementId :'userfile',
     dataType  : 'json',
     data    : {
      'title'      : $('#title').val()
     },
     success : function (data, status)
     {
      if(data.status != 'error')
      {
        $('#files').html('<p>Reloading files...</p>');
        refresh_files();
        $('#title').val('');
      }
      alert(data.msg);
     }
   });
   return false;
  });
});

Javascript hijacked the submission of the form and ajaxfileupload took over. In fact, an iframe was created in the background and the data was submitted.

I just submitted the value of # title for ajax, and more fields can be submitted through parameters.

Check the returned json data, and if there are no errors, refresh the file list (below) and clear the title field. Either way, alert returns the data.

Step 3, Upload the file

Controller part

Now we are uploading files. Our URL is like this /uplaod/upload_file/, so we establish the upload_file method in the controller of uoload.


public function upload_file()
{
  $status = "";
  $msg = "";
  $file_element_name = 'userfile';
 
  if (empty($_POST['title']))
  {
   $status = "error";
   $msg = "Please enter a title";
  }
 
  if ($status != "error")
  {
   $config['upload_path'] = './files/';
   $config['allowed_types'] = 'gif|jpg|png|doc|txt';
   $config['max_size'] = 1024 * 8;
   $config['encrypt_name'] = TRUE;
 
   $this->load->library('upload', $config);
 
   if (!$this->upload->do_upload($file_element_name))
   {
     $status = 'error';
     $msg = $this->upload->display_errors('', '');
   }
   else
   {
     $data = $this->upload->data();
     $file_id = $this->files_model->insert_file($data['file_name'], $_POST['title']);
     if($file_id)
     {
      $status = "success";
      $msg = "File successfully uploaded";
     }
     else
     {
      unlink($data['full_path']);
      $status = "error";
      $msg = "Something went wrong when saving the file, please try again.";
     }
   }
   @unlink($_FILES[$file_element_name]);
  }
  echo json_encode(array('status' => $status, 'msg' => $msg));
}

We did a simple data check on the title field to see if it was empty. Load the upload library of codeigniter if it is not empty. This class library handles a lot of data validation for us.

Then, we uploaded the file. If successful, we save title and file_name. Then we delete the temporary file, and finally, the json method returns the status and information to tell us the result.

Model part

According to most people's MVC schema concept, we should deal with database exchange in the model.

Establish files_model. php


class Files_Model extends CI_Model {
 
  public function insert_file($filename, $title)
  {
   $data = array(
     'filename'   => $filename,
     'title'    => $title
   );
   $this->db->insert('files', $data);
   return $this->db->insert_id();
  }
 
}

Folder to save uploaded files

Don't forget to create an files folder in the root directory and give it write permission.

Step 4, List of Files

After successful uploading, we need to update the file list for easy modification.

Javascript Part

Open site. js and append:


function refresh_files()
{
  $.get('./upload/files/')
  .success(function (data){
   $('#files').html(data);
  });
}

Simple application of Jquery. Ajax takes the contents of the specified url and fills it into the div of # files.

Controller part

I won't say much.


public function files()
{
  $files = $this->files_model->get_files();
  $this->load->view('files', array('files' => $files));
}

Call the method of the model to get the data, and then load it into the files view for display.

Model part


public_html/
- application/
 - - controllers/
 -  upload.php
 - - models/
 -  files_model.php
 - - views/
 -  upload.php
 -  files.php
- css/
 - - style.css
- files/
- js/
 - - AjaxFileUpload.js
 - - site.js

0

View section

New files. php view


public_html/
- application/
 - - controllers/
 -  upload.php
 - - models/
 -  files_model.php
 - - views/
 -  upload.php
 -  files.php
- css/
 - - style.css
- files/
- js/
 - - AjaxFileUpload.js
 - - site.js

1

public_html/
- application/
 - - controllers/
 -  upload.php
 - - models/
 -  files_model.php
 - - views/
 -  upload.php
 -  files.php
- css/
 - - style.css
- files/
- js/
 - - AjaxFileUpload.js
 - - site.js

2

Delete a file

Javascript Part


$('.delete_file_link').live('click', function(e) {
  e.preventDefault();
  if (confirm('Are you sure you want to delete this file?'))
  {
   var link = $(this);
   $.ajax({
     url     : './upload/delete_file/' + link.data('file_id'),
     dataType : 'json',
     success   : function (data)
     {
      files = $(#files);
      if (data.status === "success")
      {
        link.parents('li').fadeOut('fast', function() {
         $(this).remove();
         if (files.find('li').length == 0)
         {
           files.html('<p>No Files Uploaded</p>');
         }
        });
      }
      else
      {
        alert(data.msg);
      }
     }
   });
  }
});

Controller part


public_html/
- application/
 - - controllers/
 -  upload.php
 - - models/
 -  files_model.php
 - - views/
 -  upload.php
 -  files.php
- css/
 - - style.css
- files/
- js/
 - - AjaxFileUpload.js
 - - site.js

4

Model part


public_html/
- application/
 - - controllers/
 -  upload.php
 - - models/
 -  files_model.php
 - - views/
 -  upload.php
 -  files.php
- css/
 - - style.css
- files/
- js/
 - - AjaxFileUpload.js
 - - site.js

5

Well, simple application. There are no permissions involved, upload progress bars, etc.


Related articles: