我正在尝试使用codeigniter在databse中上传文件,图像正存储在文件夹中,但是我在将数据存储在databse中时遇到问题,我不知道在哪里 我错了。请谁能指导我我做错了什么?我不是Codeigniter概念的新手。
upload.php(controller)
<?php
class Upload extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper(array('form', 'url'));
}
public function index() {
$this->load->view('upload_form', array('error' => ' ' ));
}
public function do_upload() {
$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);
if ( ! $this->upload->do_upload('filename')) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
else {
$data = array('upload_data' => $this->upload->data('filename'),$this->input->post());
$this->Upload_model->saverecords($data);
//$this->load->view('upload_success', $data);
}
}
}
?>
Upload_model.php(模型)
<?php
class Upload_model extends CI_Model
{
//Insert
function saverecords($data)
{
//saving records
$this->db->insert('latest_news', $data);
}
}
?>
Upload_form.php(视图)
<html>
<head>
<title>Upload Form</title>
</head>
<body>
<?php echo $error;?>
<?php echo form_open_multipart('upload/do_upload');?>
<form action = "" method = "POST">
<input type = "file" name = "filename" size = "20" />
<br /><br />
<input type = "submit" value = "upload" />
</form>
</body>
</html>
答案 0 :(得分:0)
您两次声明<form>
!完全删除<form action = "" method = "POST">
,仅使用上面的form_open_multipart
:
<?php echo $error;?>
<?php echo form_open_multipart('upload/do_upload');?>
<input type="file" name="filename" size="20" />
<br /><br />
<input type="submit" value="upload" />
</form>
也不需要像type = "submit"
然后在您的代码中:
if ( ! $this->upload->do_upload('filename')) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
else {
//$data = array('upload_data' => $this->upload->data('filename'),$this->input->post());
$data['upload_data'] = $this->upload->data('file_name');
$this->load->model('upload_model');
$this->upload_model->saverecords($data);
//$this->load->view('upload_success', $data);
}
为了将来:
不要只执行$this->input->post()
来将键值对分配给db中的键值对。它不是很受控制,并且可能导致问题。相反,只需对其进行定义。因此,如果添加其他数据,它将看起来像:
$data = array(
'example1_fieldname' => $this->input->post('example1_fieldname');
'upload_data' => $this->upload->data('file_name');
);