[CodeIgniter] 使用 upload library 上傳檔案

分享:

要透過 CodeIgniter 來上傳檔案,可以先建立一個檔案 application/views/upload_form.php 如下:

<?php echo form_open_multipart('upload/do_upload');?>

<input type="file" name="userfile" size="20" />

<br /><br />

<input type="submit" value="upload" />

</form>

這裡透過 form_open_multipart() 來建立 form 標籤,裡面帶的參數是 post 的網址。

接著在 Controller 裡如此設定:

class Upload extends CI_Controller {

        public function __construct()
        {
                parent::__construct();
                $this->load->helper(array('form', 'url'));
        }

        public function index()
        {
                $this->load->view('upload_form');
        }

        public function do_upload()
        {
                $config['upload_path']          = './uploads/';
                $config['allowed_types']        = 'gif|jpg|png';
                $config['max_size']             = 100;
                $config['max_width']            = 1024;
                $config['max_height']           = 768;

                $this->load->library('upload', $config);

                if ( ! $this->upload->do_upload('userfile'))
                {
                        $error = array('error' => $this->upload->display_errors());

                        var_dump($error);
                }
                else
                {
                        $data = array('upload_data' => $this->upload->data());

                       var_dump($data);
                }
        }
}

 

上面是讀取 upload 的 libary,並丟入設定值,設定值主要是來設定要上傳的資料夾位置。

$this->load->library('upload', $config);

之後就可以測試是否成功了。

官方文件說明

 

課程推薦

ChatGPT X Clipchamp AI 生成影片、配音與字幕應用實戰班

ChatGPT X Clipchamp AI 生成影片、配音與字幕應用實戰班

輸入折扣碼 TC1451JAN 還可以額外獲得 NT$500 優惠喔。

和我們交流

加入我們的社群,裡面會有一些技術的內容、有趣的技術梗,以及職缺的分享,歡迎和我們一起討論。