[英]Codeigniter & Datamapper: Saving uploaded image to database doesn't work
我正在嘗試使用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>
嘗試這個。
相反,實例化一個新的Article_Model
在do_upload
方法,只需從返回圖像名稱do_upload
方法,並設置的url屬性Article_Model
其保存到數據庫之前。
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'];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.