CodeIgniter学习笔记(十四)——CI中的文件上传

首先通过控制器的方法跳转至视图

public function file()
{
    $this->load->helper('url');
    $this->load->view('file');
}

在视图中创建一个表单用于选择并上传文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <form action="<?php echo site_url('index.php/user/upload'); ?>" method="post" enctype="multipart/form-data">
        <input type="file" name="pic" />
        <input type="submit" name="submit" value="submit">
    </form>
</body>
</html>

其中,要注意第一个input的name属性,这个属性后面要用,在表单中将action设置为一个控制器方法,编写对应的控制器方法

public function upload()
{
    // 上传文件到服务器目录
    $config['upload_path'] = './upload';
    // 允许上传哪些类型
    $config['allowed_types'] = 'gif|png|jpg|jpeg';
    // 上传后的文件名,用uniqid()保证文件名唯一
    $config['file_name'] = uniqid();
            
    // 加载上传库
    $this->load->library('upload', $config);
    // 上传文件,这里的pic是视图中file控件的name属性
    $result = $this->upload->do_upload('pic');
    // 如果上传成功,获取上传文件的信息
    if ($result) 
    {
        var_dump($this->upload->data());
    }
}
这样就完成文件上传了
原文地址:https://www.cnblogs.com/iamsupercola/p/4638326.html