将图像路径上载到文件夹名称上载中的db和image

时间:2012-11-07 15:54:20

标签: codeigniter codeigniter-2 codeigniter-form-helper

这是控制器:

public function category()
    {
        if($this->form_validation->run()==FALSE)
        {
            $this->load->view('admin/home');
        }
        else{
                $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);
                $image_data=$_POST['file'];
            if ( ! $this->upload->do_upload())
            {
                // no file uploaded or failed upload
                $error = array('error' => $this->upload->display_errors());
                $this->load->view('admin/home', $error);
            }
            else
            {
                // success
                $data = array('upload_data' => $this->upload->data());
                $this->your_upload_model->add($title, $description, $data["file_name"]);

                $this->load->view('upload_success', $data);
            }
        }

    }

这是观点:

<?php echo validation_errors();?>
        <?php echo form_open_multipart('login/category');?>
        <?php
        if(isset($error))
        {
            echo $error;
        }
        ?>
<table>
<tr>
        <td align=right>Logo:</td>

        <td><input type="file" name="file"></td>
        <td><input type="submit" value="submit"></td>

        </tr>

        </table> 

我遇到两个错误:

  1. 消息:未定义索引:文件
  2. 您没有选择要上传的文件。
  3. 即使文本字段名称相同,我也使用form_open_multipart()。此外,图片未上传且错误无效。

2 个答案:

答案 0 :(得分:0)

首先,$_POST['file']无法正常工作,但其次,您需要在do_upload()中提供HTML字段名称:

if ( ! $this->upload->do_upload('file'))
{
...
}

另外,请删除$image_data=$_POST['file'];因为它无论如何都无法工作。您已经在使用$this->upload->data(),这是获取上传文件数据的正确方法。

$this->upload->do_upload()没有字段名称的原因是因为如果未提供参数,它会查找字段name="userfile"。您正在使用name="file"

答案 1 :(得分:0)

将此代码用于第一个问题:

public function category()
{
 if (array_key_exists('submit', $_POST)) {
  ---------You can enter the remaining code here............
 }
}

第二个:

if ( ! $this->upload->do_upload("file"))
{
 -----------code here----------
}