Codeigniter& Datamapper:将上传的图像保存到数据库不起作用

时间:2014-03-31 19:34:24

标签: php codeigniter datamapper codeigniter-datamapper

我正在尝试使用datamapper来帮助我将file_name存储在数据库中。首先,我使用Codeigniter手册中给出的do_upload的基本示例来完成它,最后我编写了3行datamapper来查看带有id和url的简单表。我运行它并保存得很好。

现在的问题是当我尝试在add_article方法中调用do_upload函数时,所以当一个文章上传了图像以保存文章的所有细节+上传的图像名称。然而,它不起作用,我尝试各种类型。这就是我所拥有的:

在我的控制器中:

public function add_article($id = NULL)
{
    $articles = new Article_model();
    $article = $articles->where('id', $id)->get();

    $article->title = $this->input->post('title');
    $article->text = $this->input->post('text');


    // Try to upload the image
    if ($this->input->post('submit'))
    {
        $this->do_upload();
    }

    if ($article->save())
    {
        echo '<p>You have successfully added an article</p>';
        redirect('admin/article/');
    }
    else
    {
        echo '<p>' . $article->error->string . '</p>';
    }
}

   public function do_upload()
{
    $config = array(
        'allowed_types' => 'jpg|jpeg|gif|png',
        'upload_path' => $this->gallery_path,
        );

    $this->load->library('upload' , $config);
    $this->upload->do_upload();
    $image_data = $this->upload->data();

    $article = new Article_model();
    $article->url = $image_data['file_name'];
    $article->save();


}

我的观点:

<?php echo form_open_multipart('admin/article/add_article'); ?>
<table class="table">
    <tr>
        <td>Title</td>
        <td><?php echo form_input('title', set_value('title', $article->title)); ?></td>
    </tr>
    <tr>
        <td>Image</td>
        <td><?php echo form_upload('userfile'); ?></td>
    </tr>
    <tr>
        <td>Body</td>
        <td><?php echo form_textarea('text', set_value('text' , $article->text), 'class="tinymce"'); ?></td>
    </tr>
    <tr>
        <td></td>
        <td><?php echo form_submit('submit', 'Save', 'class="btn btn-primary"'); ?></td>
    </tr>       
</table>

1 个答案:

答案 0 :(得分:0)

试试这个。

不是在Article_Model方法中实例化新的do_upload,只需从do_upload方法返回图像名称,并在保存之前设置Article_Model的url属性它到数据库。

public function add_article($id = NULL)
{
    $articles = new Article_model();
    $article = $articles->where('id', $id)->get();

    $article->title = $this->input->post('title');
    $article->text = $this->input->post('text');


    // Try to upload the image
    if ($this->input->post('submit'))
    {
        $article->url = $this->do_upload();
    }

    if ($article->save())
    {
        echo '<p>You have successfully added an article</p>';
        redirect('admin/article/');
    }
    else
    {
        echo '<p>' . $article->error->string . '</p>';
    }
}

public function do_upload()
{
    $config = array(
    'allowed_types' => 'jpg|jpeg|gif|png',
    'upload_path' => $this->gallery_path,
    );

    $this->load->library('upload' , $config);
    $this->upload->do_upload();
    $image_data = $this->upload->data();

    return $image_data['file_name'];
}