例子一:
/**
* 多文件上傳
*
* @author Dream <dream@shanjing-inc.com>
*/
public function multiple_uploads() {
//載入所需類庫
$this->load->library('upload');
//配置上傳參數
$upload_config = array(
'upload_path' => '',
'allowed_types' => 'jpg|png|gif',
'max_size' => '500',
'max_width' => '1024',
'max_height' => '768',
);
$this->upload->initialize($upload_config);
//循環處理上傳文件
foreach ($_FILES as $key => $value) {
if (!empty($key['name'])) {
if ($this->upload->do_upload($key)) {
//上傳成功
print_r($this->upload->data());
} else {
//上傳失敗
echo $this->upload->display_errors();
}
}
}
}
例子二:
function upload() {
$config['upload_path'] = './uploads/';
/*這裡的uploads是相對於index.php的,也就是入口文件,這個千萬不要弄錯哦!
否則就會報錯"The upload path does not appear to be valid.";
*/
$config['allowed_types'] = 'gif|jpg|png';
/*我試著去上傳其它類型的文件,這裡一定要注意順序!
A problem was encountered while attempting to move the uploaded file to the final destination.
這個錯誤一般是上傳文件的文件名不能是中文名,這個很郁悶!還未解決,大家可以用其它方法,重新改一下文件名就可以解決了!
$config['allowed_types'] = 'zip|gz|png|gif|jpg';(正確)
$config['allowed_types'] = 'png|gif|jpg|zip|gz';(錯誤)
*/
$config['max_size'] = '1024';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$config['file_name'] = time(); //文件名不使用原始名
$this->load->library('upload', $config);
if(!$this->upload->do_upload()) {
echo $this->upload->display_errors();
}else{
$data['upload_data']=$this->upload->data(); //文件的一些信息
$img=$data['upload_data']['file_name']; //取得文件名
echo $img."<br>";
foreach($data['upload_data'] as $item => $value){
echo $item.":".$value."<br>";
}
}
}
本地地址/CodeIgniter/index.php?/
本地地址/CodeIgniter/index.php?/welcome
本地地址/CodeIgniter/index.php?/welcome/
本地地址/CodeIgniter/index.php?/welcome/index
本地地址/CodeIgniter/index.php?/welcome/index/
試試加上?
因為使用上傳類你可以設置上傳目錄
所以這個時候其實你是知道直接目錄的,那對應的存入數據庫只要存儲文件名稱就可以了
如果目錄是變動的(例如按年月日變動),因為也是你事先知道的,也可以組織好對應的相對路徑存儲到數據庫
如果寫在對應的配置文件中,即可當變量使用了