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());
    }
}
這樣就完成文件上傳了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM