前端程式碼
<html>
<form action="ci/CodeIgniter_2.2.0/index.php/upload/up" method="post" enctype="multipart/form-data">
<input type="file" name="upfile" />
<input type="submit" name="sub" value="提交" />
</form>
</html>
控制器:
定義一個陣列,設定一些與上傳相關的引數
$config[`upload_path`] = `./uploads/`;
//設定允許上傳的型別
$config[`allowed_types`] = `gif|jpg|png`;
$config[`max_size`] = `100`;
//如果是圖片還可以設定最大高度和寬度
$config[`max_height`] = 768;
$config[`max_width`] = 1024;
呼叫CI的上傳通用類,並執行上傳
//upload為呼叫的類名,全小寫
$this->load->library(`upload`,$config);
//如果上傳框的name寫的是userfile,那就不用傳引數了,如果不是,把name的值傳進去
$this->upload->do_upload(`上傳框的name`);
接收出錯資訊或成功資訊
//出錯資訊
$error = array(`error` => $this->upload->display_error());
//成功資訊
$data = array(`upload_data` => $this->upload->data());
<?php
if ( ! defined(`BASEPATH`)) exit(`No direct script access allowed`);
class Upload extends CI_Controller {
//顯示帶表單的檢視
public function index(){
$this->load->view(`up`);
}
//顯示上傳資訊
public function up(){
$config[`upload_path`] = `./uploads/`;
$config[`allowed_types`] = `gif|jpg|png`;
$config[`max_size`] = "2000";
$this->load->library(`upload`,$config);
//列印成功或錯誤的資訊
if($this->upload->do_upload(`upfile`))
{
$data = array("upload_data" => $this->upload->data());
var_dump($data);
}
else
{
$error = array("error" => $this->upload->display_errors());
var_dump($error);
}
}
}