要透過 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);
之後就可以測試是否成功了。