CodeIgniter 的文件上传类允许文件被上传。您可以设置指定上传某类型的文件及指定大小的文件。
上传文件普遍的过程:
- 一个上传文件用的表单,允许用户选择一个文件并上传它。
- 通过 $this->load->library('upload', $config);控制文件上传的路径,格式和大小。
- 当这个表单被提交,该文件被上传到指定的目录。
- 同时,该文件将被验证是否符合您设定的要求。
<pre name="code" class="php">public function do_upload()
{
$this->load->helper(array('form', 'url'));
/*处理图片文件*/
/*上传图片配置项*/
$config1['upload_path'] = './source/uploads/picture/';
$config1['allowed_types'] = 'gif|jpg|png';
$config1['encrypt_name'] = 'true'; //是否退文件名加密
$config1['max_size'] = '2000';
$config1['max_width'] = '1600';
$config1['max_height'] = '900';
$this->load->library('upload', $config1);
if ($this -> upload -> do_upload('images'))
{
$load = array('upload_data' => $this -> upload -> data());
$url = $config1['upload_path'].$load['upload_data']['file_name'];
$upinfo = array('images' => $url); //将文件的相对路径取出
}
/*处理音频文件*/
/*上传音频配置项*/
$config2['upload_path'] = './source/uploads/music/';
$config2['allowed_types'] = 'mp3|ogg';
$config2['encrypt_name'] = 'true';
$config2['max_size'] = '8000';
//调用初始化函数 initialize 来加载音频配置项
$this->upload->initialize($config2);
if ($this -> upload -> do_upload('music'))
{
$load = array('upload_data' => $this -> upload -> data());
$url = $config2['upload_path'].$load['upload_data']['file_name'];
$upinfo = array('music' => $url); //将文件的相对路径取出
}
var_dump($upinfo); /*打印文件路径, 方便存入数据库*/
}
上传不同类型文件需要不同的配置项,分别处理不同类型文件时,需要
$this->upload->initialize($config2);来加载不同的配置项。