本文实例分析了CI框架实现优化文件上传及多文件上传的方法。,具体如下:
最近一直在研究Codeigniter框架,开发项目写到文件上传的时候发现大部分程序员使用Codeigniter框架的文件上传类编写上传方法的时候写的都存在这代码冗余(或者说代码重复利用率低、比较消耗资源。)故而我研究出一个稍微优化一点的上传方法。并且在查找资料时发现,Codeigniter框架同时上传多个文件比较困难,所以在优化方法的同时我又研究了一下如何使用Codeigniter框架实现同时上传多个文件。下面就来和大家分享一下,感兴趣的同学可以关注一下,同时欢迎大家指正错误。
1、优化文件上传方法
Codeigniter手册里面的那种大家常用的方法在这里就不重复描述了,下面直接说如何对方法进行优化以达到降低代码冗余,提高代码重复利用率的目的。
a) 首先在 “ application/config ” 新建 " upload.php " 配置文件
在 “ application/config ” 新建 " upload.php" 配置文件,在里面写入上传的配置参数。
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
//上传的参数配置
$config['upload_path'] = './public/uploads/';
$config['allowed_types'] = 'gif|png|jpg';
$config['max_size'] = 100;
$config['max_width'] = '1024';
$config['max_height'] = '768';
注意:upload_path参数所代表的路径文件夹你已经在项目中创建完毕!
b) 在控制器的构造函数中加载文件上传类
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* 控制器
*/
class Brand extends Admin_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('brand_model');
$this->load->library('form_validation');
//激活分析器以调试程序
$this->output->enable_profiler(TRUE);
//配置中上传的相关参数会自动加载
$this->load->library('upload');
}
}
注意:我们在第一步创建的 “ upload.php ” 文件中的上传配置信息会在这里会自动进行加载。
c) 编写上传方法执行do_upload()方法进行文件上传
public function insert()
{
//设置验证规则
$this->form_validation->set_rules('brand_name','名称','required');
if($this->form_validation->run() == false){
//未通过验证
$data['message'] = validation_errors();
$data['wait'] = 3;
$data['url'] = site_url('admin/brand/add');
$this->load->view('message.html',$data);
}else{
//通过验证,处理图片上传
if ($this->upload->do_upload('logo')) { //logo为前端file控件名
//上传成功,获取文件名
$fileInfo = $this->upload->data();
$data['logo'] = $fileInfo['file_name'];
//获取表单提交数据
$data['brand_name'] = $this->input->post('brand_name');
$data['url'] = $this->input->post('url');
$data['brand_desc'] = $this->input->post('brand_desc');
$data['sort_order'] = $this->input->post('sort_order');
$data['is_show'] = $this->input->post('is_show');
//调用模型完成添加动作
if($this->brand_model->add_brand($data)){
$data['message'] = "添加成功";
$data['wait'] = 3;
$data['url'] = site_url('admin/brand/index');
$this->load->view('message.html',$data);
}else{
$data['message'] = "添加失败";
$data['wait'] = 3;
$data['url'] = site_url('admin/brand/add');
$this->load->view('message.html',$data);
}
}else{
//上传失败
$data['message'] = $this->upload->display_errors();
$data['wait'] = 3;
$data['url'] = site_url('admin/brand/add');
$this->load->view('message.html',$data);
}
}
}







