最近幾天正在做一個小型CMS,用到圖片上傳了,想利於CodeIgniter的上傳類去實現,但測試中有好多問題,我把經過和要注意的地方分享一下!
復制代碼 代碼如下:
<?php echo form_open_multipart('picture/upload');?>
<?php echo form_upload('userfile');?>
/*注意,這裡是userfile,$this->upload->do_upload(),這裡do_upload默認上傳文件的表單名為userfile;
當然也可以使用do_upload($filename),這裡的$filename一定要和form_upload()裡面的字符串一致.
我在這裡范了糊塗,最後看了手冊才明白,希望大家注意哦!
*/
<?php echo form_close();?>
controller代碼:
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>";
}
}
}