[英]How to upload an image and save it to database in Codeigniter?
我知道这个问题已经被问过无数次,但是对于初学者来说,所有这些问题都有些困难。
因此,我要寻找的是如何创建一个简单的按钮,该按钮上传图像并获取其full_path并将其保存在表单的隐藏输入中,因此当我单击Submit时,该表单会将路径与其他输入一起插入,因此图像将被上传到目录中。
这是一个简单的项目,一个基本的博客页面,在这里我需要保存以下输入:1.图片2.标题3.正文
我唯一无法完成的是图像部分。
所以这是视图代码:
<h1>Add New Post</h1>
<br />
<?=form_open('admin/add_post');?>
<p>
<input type="text" name="title" />
</p>
<input hidden="hidden" name="date" value="<?php echo date('d-m-y');?>"/>
<p>
<textarea id="textarea" name="body" rows="10"></textarea>
</p>
<p>
<input type="submit" value="Submit Post" />
</p>
</form>
当您单击提交时,这是控制器:
// Adds new posts to the database table
function add_post()
{
$this->form_validation->set_rules('title', 'Title', 'required|min_length[2]');
$this->form_validation->set_rules('body', 'Body', 'required|min_length[2]');
if ($this->form_validation->run() == TRUE) {
// INSERTING GOES HERE..
$this->db->insert('entries', $_POST);
redirect('admin/posts');
}
else {
redirect('admin/add');
}
}
因此,我需要有人告诉我如何编写上载功能,以将图像上载到同一页面和同一表格上,并将其路径保存到数据库。
我可以使它保存路径,但是我想先获取路径并将其添加到隐藏输入EX中的相同表单中:
请我真的需要您的帮助,如果您对如何帮助我有任何想法,请发表您的答案。
提前致谢。
使用CodeIgniter实现这一点非常简单。
我将使用3.1.0版参考:
视图:
<?php echo form_open_multipart('upload/do_upload');?>
<input type="file" name="userfile" size="20" />
<br /><br />
<input type="submit" value="upload" />
</form>
控制器:
public function do_upload() {
$fileData = array();
// File upload script
$this->upload->initialize(array(
'upload_path' => './uploads/',
'overwrite' => false,
'max_filename' => 300,
'encrypt_name' => true,
'remove_spaces' => true,
'allowed_types' => 'gif|jpg|png',
'max_size' => 100,
'xss_clean' => true,
));
$this->form_validation->set_rules('title', 'Title', 'required|min_length[2]');
$this->form_validation->set_rules('body', 'Body', 'required|min_length[2]');
if ($this->form_validation->run() == TRUE) {
if ($this->upload->do_upload('userfile')) {
$data = $this->upload->data(); // Get the file data
$fileData[] = $data; // It's an array with many data
// Interate throught the data to work with them
foreach ($fileData as $file) {
$file_data = $file;
}
var_dump($file_data);
$this->db->insert('entries', array(
// So you can work with the values, like:
'title' => $this->input->post('title', true), // TRUE is XSS protection
'body' => $this->input->post('body', true),
'file_name' => $file_data['file_name'],
'file_ext' => $file_data['file_ext'],
));
$this->session->set_flashdata('success', 'Form submitted successfully');
redirect('admin/add');
} else {
$this->session->set_flashdata('error', $this->upload->display_errors());
redirect('admin/add');
}
} else {
$this->session->set_flashdata('error', validation_errors());
redirect('admin/add');
}
}
您可以使用var_dump查看可用的数据,或查看文档(在底部)
https://www.codeigniter.com/userguide3/libraries/file_uploading.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.