当前位置:首页 > CMS教程 > 其它CMS > 列表

Codeigniter里的无刷新上传的实现代码

发布:smiling 来源: PHP粉丝网  添加日期:2021-11-17 14:22:28 浏览: 评论:0 

这篇文章主要介绍了Codeigniter里的无刷新上传的实现代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧。

好久没有更新了,写点吧算是翻译吧,纯原创没空啊XD

Codeigniter还是很好用的,淡水一直很推崇。说是codeigniter里的无刷新上传吧,fashion 一点的说法就是利用AJAX技术上传。其中用到了Jquery和 AjaxFileUpload 。

先建个表

  1. CREATE TABLE `files` ( 
  2.  `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, 
  3.  `filename` VARCHAR(255) NOT NULL, 
  4.  `title` VARCHAR(100) NOT NULL 
  5. ); 

文件的目录结构如下:

  1. public_html/ 
  2. - application/ 
  3. ―- controllers/ 
  4. ―― upload.php 
  5. ―- models/ 
  6. ―― files_model.php 
  7. ―- views/ 
  8. ―― upload.php 
  9. ―― files.php 
  10. - css/ 
  11. ―- style.css 
  12. - files/ 
  13. - js/ 
  14. ―- AjaxFileUpload.js 
  15. ―- site.js 

第一步,建立表单

看上去就一个title文本字段,一个文件框,一个提交按钮,还有一个files的div。

控制器部分

首先,我们要建一个上传的表单和一个upload的Controller。在index方法里渲出upload的视图,如下:

  1. class Upload extends CI_Controller 
  2. { 
  3.   public function __construct() 
  4.   { 
  5.    parent::__construct(); 
  6.    $this->load->model('files_model'); 
  7.    $this->load->database(); 
  8.    $this->load->helper('url'); 
  9.   } 
  10.    
  11.   public function index() 
  12.   { 
  13.    $this->load->view('upload'); 
  14.   } 
  15. } 

我们已经在构造里加载了files_model,所以可以使用files_model里的方法。

建立表单视图

视图文件upload.php,包含了我们的上传表单。

  1. <!doctype html> 
  2. <html> 
  3. <head> 
  4.   <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> 
  5.   <script src="<?php echo base_url()?>js/site.js"></script> 
  6.   <script src="<?php echo base_url()?>js/ajaxfileupload.js"></script> 
  7.   <link href="<?php echo base_url()?>css/style.css" rel="external nofollow" rel="stylesheet" /> 
  8. </head> 
  9. <body> 
  10.   <h1>Upload File</h1> 
  11.   <form method="post" action="" id="upload_file"> 
  12.    <label for="title">Title</label> 
  13.    <input type="text" name="title" id="title" value="" /> 
  14.    
  15.    <label for="userfile">File</label> 
  16.    <input type="file" name="userfile" id="userfile" size="20" /> 
  17.    
  18.    <input type="submit" name="submit" id="submit" /> 
  19.   </form> 
  20.   <h2>Files</h2> 
  21.   <div id="files"></div> 
  22. </body> 
  23. </html> 

我们在文件开始就加载了jquery,ajaxfileupload和我们自己的site.js文件。Id为files的div是我们显示上传文件列表用的。

一些简单的css

在css下建立style.css

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

第二步,Javascript

在js下建立site.js

  1. $(function() { 
  2.   $('#upload_file').submit(function(e) { 
  3.    e.preventDefault(); 
  4.    $.ajaxFileUpload({ 
  5.      url     :'./upload/upload_file/', 
  6.      secureuri   :false, 
  7.      fileElementId :'userfile', 
  8.      dataType  : 'json', 
  9.      data    : { 
  10.       'title'      : $('#title').val() 
  11.      }, 
  12.      success : function (data, status) 
  13.      { 
  14.       if(data.status != 'error') 
  15.       { 
  16.         $('#files').html('<p>Reloading files...</p>'); 
  17.         refresh_files(); 
  18.         $('#title').val(''); 
  19.       } 
  20.       alert(data.msg); 
  21.      } 
  22.    }); 
  23.    return false; 
  24.   }); 
  25. }); 

Javascript劫持了表单的提交,并由ajaxfileupload接管。其实是在后台创建了一个iframe并提交了数据。

我只是ajax提交了#title的值,可以通过参数提交更多的字段。

检查返回的json数据,如果没有错误,就刷新文件列表(下文有),清除title字段。不管怎样,都alert出返回的数据。

第三步,上传文件

控制器部分

现在开始上传文件了。我们的URL是这样的 /uplaod/upload_file/,所以,我们在uoload的控制器里建立upload_file方法。

  1. public function upload_file() 
  2. { 
  3.   $status = ""; 
  4.   $msg = ""; 
  5.   $file_element_name = 'userfile'; 
  6.    
  7.   if (emptyempty($_POST['title'])) 
  8.   { 
  9.    $status = "error"; 
  10.    $msg = "Please enter a title"; 
  11.   } 
  12.    
  13.   if ($status != "error") 
  14.   { 
  15.    $config['upload_path'] = './files/'; 
  16.    $config['allowed_types'] = 'gif|jpg|png|doc|txt'; 
  17.    $config['max_size'] = 1024 * 8; 
  18.    $config['encrypt_name'] = TRUE; 
  19.    
  20.    $this->load->library('upload', $config); 
  21.    
  22.    if (!$this->upload->do_upload($file_element_name)) 
  23.    { 
  24.      $status = 'error'; 
  25.      $msg = $this->upload->display_errors('', ''); 
  26.    } 
  27.    else 
  28.    { 
  29.      $data = $this->upload->data(); 
  30.      $file_id = $this->files_model->insert_file($data['file_name'], $_POST['title']); 
  31.      if($file_id) 
  32.      { 
  33.       $status = "success"; 
  34.       $msg = "File successfully uploaded"; 
  35.      } 
  36.      else 
  37.      { 
  38.       unlink($data['full_path']); 
  39.       $status = "error"; 
  40.       $msg = "Something went wrong when saving the file, please try again."; 
  41.      } 
  42.    } 
  43.    @unlink($_FILES[$file_element_name]); 
  44.   } 
  45.   echo json_encode(array('status' => $status, 'msg' => $msg)); 
  46. } 

我们对title字段做了个简单的数据检查,看看他是否为空。不为空就加载codeigniter的upload库。这个类库为我们处理了很多的数据验证。

接着,我们上传文件了。如果成功我们保存title和file_name。然后我们删除了临时文件,最后,json方法返回了状态和信息,来告诉我们结果。

模型部分

按大多数人的MVC模式理念,我们应该在模型里处理数据库交换。

建立files_model.php

  1. class Files_Model extends CI_Model { 
  2.    
  3.   public function insert_file($filename, $title) 
  4.   { 
  5.    $data = array( 
  6.      'filename'   => $filename, 
  7.      'title'    => $title 
  8.    ); 
  9.    $this->db->insert('files', $data); 
  10.    return $this->db->insert_id(); 
  11.   } 
  12.    
  13. } 

保存上传文件的文件夹

不要忘记在根目录建立个files文件夹,并给他写入权限。

第四步,文件列表

成功上传后,我们需要更新文件列表,方便修改。

Javascript部分

打开site.js,在后面追加:

  1. function refresh_files() 
  2. { 
  3.   $.get('./upload/files/') 
  4.   .success(function (data){ 
  5.    $('#files').html(data); 
  6.   }); 
  7. } 

Jquery的简单应用。Ajax取得指定url的内容,填充到#files的div里。

控制器部分

不多说了。

  1. public function files() 
  2. { 
  3.   $files = $this->files_model->get_files(); 
  4.   $this->load->view('files', array('files' => $files)); 
  5. } 

调用模型的方法取得数据,再加载到files视图里显示。

模型部分

  1. public function get_files() 
  2. { 
  3.   return $this->db->select() 
  4.      ->from('files') 
  5.      ->get() 
  6.      ->result(); 
  7. } 

视图部分

新建files.php视图

  1. <?php 
  2. if (isset($files) && count($files)) 
  3. { 
  4.   ?> 
  5.      
  6.  
  7.      <?php 
  8.      foreach ($files as $file) 
  9.      { 
  10.       ?> 
  11.         
  12.  
  13.         Delete 
  14.         <?php echo $file->title?> 
  15.           
  16.  
  17.         <?php echo $file->filename?> 
  18.         
  19.  
  20.       <?php 
  21.      } 
  22.      ?> 
  23.  
  24. <?php 
  25. } 
  26. else 
  27. { 
  28.   ?> 
  29.     
  30. No Files Uploaded 
  31.  
  32.  
  33.   <?php 
  34. } 
  35. ?> 

删除文件

Javascript部分

  1. $('.delete_file_link').live('click', function(e) { 
  2.   e.preventDefault(); 
  3.   if (confirm('Are you sure you want to delete this file?')) 
  4.   { 
  5.    var link = $(this); 
  6.    $.ajax({ 
  7.      url     : './upload/delete_file/' + link.data('file_id'), 
  8.      dataType : 'json', 
  9.      success   : function (data) 
  10.      { 
  11.       files = $(#files); 
  12.       if (data.status === "success") 
  13.       { 
  14.         link.parents('li').fadeOut('fast', function() { 
  15.          $(this).remove(); 
  16.          if (files.find('li').length == 0) 
  17.          { 
  18.            files.html('<p>No Files Uploaded</p>'); 
  19.          } 
  20.         }); 
  21.       } 
  22.       else 
  23.       { 
  24.         alert(data.msg); 
  25.       } 
  26.      } 
  27.    }); 
  28.   } 
  29. }); 

控制器部分

  1. public function delete_file($file_id) 
  2. { 
  3.   if ($this->files_model->delete_file($file_id)) 
  4.   { 
  5.    $status = 'success'; 
  6.    $msg = 'File successfully deleted'; 
  7.   } 
  8.   else 
  9.   { 
  10.    $status = 'error'; 
  11.    $msg = 'Something went wrong when deleteing the file, please try again'; 
  12.   } 
  13.   echo json_encode(array('status' => $status, 'msg' => $msg)); 
  14. } 

模型部分

  1. public function delete_file($file_id) 
  2. { 
  3.   $file = $this->get_file($file_id); 
  4.   if (!$this->db->where('id', $file_id)->delete('files')) 
  5.   { 
  6.    return FALSE; 
  7.   } 
  8.   unlink('./files/' . $file->filename); 
  9.   return TRUE; 
  10. } 
  11.    
  12. public function get_file($file_id) 
  13. { 
  14.   return $this->db->select() 
  15.      ->from('files') 
  16.      ->where('id', $file_id) 
  17.      ->get() 
  18.      ->row(); 
  19. } 

嗯,简单的应用。没有涉及的权限、上传的进度条等。

Tags: Codeigniter无刷新上传

分享到: