It's been a long time since I updated it, so I can write it as a translation. I don't have time to write it. I'm not free of original creation. XD
Codeigniter is still very useful, and Tamsui has always praised it. It's called a refresh-free upload in codeigniter. Fashion One thing to say is to use AJAX technology to upload. Jquery and AjaxFileUpload are used.
Create 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/ ―― ―- models/ ―― files_model.php ―- views/ ―― ―― - css/ ―- - files/ - js/ ―- ―-
The first step is to create a form
It looks like a title text field, a file box, a submit button, and a file div.
Controller part
First, we need to create an upload form and an upload controller. Render the upload view in the 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 loaded files_model in the construct, so we can use the method in files_model.
Create a form view
View file, containing our upload form.
<!doctype html> <html> <head> <script src="/ajax/libs/jquery/1.6.2/"></script> <script src="<?php echo base_url()?>js/"></script> <script src="<?php echo base_url()?>js/"></script> <link href="<?php echo base_url()?>css/" rel="external nofollow" rel="stylesheet" /> </head> <body> <h1>Upload File</h1> <form method="post" action="" > <label for="title">Title</label> <input type="text" name="title" value="" /> <label for="userfile">File</label> <input type="file" name="userfile" size="20" /> <input type="submit" name="submit" /> </form> <h2>Files</h2> <div ></div> </body> </html>
We load jquery, ajaxfileupload and our own files at the beginning of the file. The div with Id is files that we use to display the uploaded file list.
Some simple css
Created 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
Created under js
$(function() { $('#upload_file').submit(function(e) { (); $.ajaxFileUpload({ url :'./upload/upload_file/', secureuri :false, fileElementId :'userfile', dataType : 'json', data : { 'title' : $('#title').val() }, success : function (data, status) { if( != 'error') { $('#files').html('<p>Reloading files...</p>'); refresh_files(); $('#title').val(''); } alert(); } }); return false; }); });
Javascript hijacks the form's submission and takes over by ajaxfileupload. In fact, an iframe was created in the background and submitted the data.
I just ajax submitted the value of #title, and can submit more fields via arguments.
Check the returned json data. If there is no error, refresh the file list (below) and clear the title field. In any case, the returned data is alerted.
Step 3: Upload the file
Controller part
Now you start uploading files. Our URL is like /uplaod/upload_file/, so we set up the upload_file method in the uoload controller.
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 is empty. Load codeigniter's upload library without being empty. This class library handles a lot of data verification for us.
Then, we uploaded the file. If successful we save the title and file_name. Then we deleted the temporary file, and finally, the json method returns the status and information to tell us the result.
Model part
According to the MVC model philosophy of most people, we should handle database exchange in the model.
Create 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(); } }
Save the folder where the uploaded file is
Don't forget to create a file folder in the root directory and give it permission to write.
Step 4, File List
After successful upload, we need to update the file list for easy modification.
Javascript part
Open and add:
function refresh_files() { $.get('./upload/files/') .success(function (data){ $('#files').html(data); }); }
Simple application of Jquery. Ajax gets the content 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 model method to obtain the data, and then load it into the files view to display.
Model part
public function get_files() { return $this->db->select() ->from('files') ->get() ->result(); }
View part
Create a new view
<?php if (isset($files) && count($files)) { ?> <?php foreach ($files as $file) { ?> Delete <?php echo $file->title?> <?php echo $file->filename?> <?php } ?>
<?php } else { ?> No Files Uploaded <?php } ?>
Delete files
Javascript part
$('.delete_file_link').live('click', function(e) { (); if (confirm('Are you sure you want to delete this file?')) { var link = $(this); $.ajax({ url : './upload/delete_file/' + ('file_id'), dataType : 'json', success : function (data) { files = $(#files); if ( === "success") { ('li').fadeOut('fast', function() { $(this).remove(); if (('li').length == 0) { ('<p>No Files Uploaded</p>'); } }); } else { alert(); } } }); } });
Controller part
public function delete_file($file_id) { if ($this->files_model->delete_file($file_id)) { $status = 'success'; $msg = 'File successfully deleted'; } else { $status = 'error'; $msg = 'Something went wrong when deleteing the file, please try again'; } echo json_encode(array('status' => $status, 'msg' => $msg)); }
Model part
public function delete_file($file_id) { $file = $this->get_file($file_id); if (!$this->db->where('id', $file_id)->delete('files')) { return FALSE; } unlink('./files/' . $file->filename); return TRUE; } public function get_file($file_id) { return $this->db->select() ->from('files') ->where('id', $file_id) ->get() ->row(); }
Well, a simple application. There are no permissions involved, upload progress bars, etc.
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.