我是Codeigniter新手,我正在尝试获取上传图像的文件名,以便我可以将其保存在数据库中。 我有两个模型,homemodel处理我的数据库和image_upload_model处理图像上传。 一切正常,除了我不知道如何将图像文件名发布到数据库
image_upload_model.php
<?php
class Image_upload_model extends CI_Model {
var $image_path;
//constructor containing the image path
function Image_upload_model() {
$this->image_path = realpath(APPPATH.'../assets/img');
}
//uploading the file
function do_upload() {
$config = array(
'allowed_types' => 'jpg|jpeg|gif|png',
'upload_path' => $this->image_path
);
$this->load->library('upload',$config);
$this->upload->do_upload();
}
}
?>
homemodel.php
<?php
class homeModel extends CI_Model {
//inserting into the table tenants
function addTenants() {
$this->load->model('Image_upload_model');
$data = array(
'Fname' => $this->input->post('Fname'),
'Lname' => $this->input->post('Lname'),
'contact' => $this->input->post('contact'),
'email' => $this->input->post('email'),
'location' => $this->input->post('location'),
'img_url' => " "//the filename of the image should go here
);
$this->db->insert('tenants', $data);
}
}
?>
控制器
的 homecontroller.php
<?php
class HomeController extends CI_Controller {
public function index() {
$this->load->helper('form');
$this->load->helper('html');
$this->load->model('homemodel');
$this->load->model('Image_upload_model');
if ($this->input->post('submit') == 'Submit') {
$this->homemodel->addTenants();
echo 'inserted';
$this->Image_upload_model->do_upload();
echo 'image uploaded';
}
$this->load->view('index.php');
}
}
?>
感谢任何帮助,谢谢!
答案 0 :(得分:17)
你可以像这样获得文件名
$upload_data = $this->upload->data();
$file_name = $upload_data['file_name'];
答案 1 :(得分:2)
在很高的层面上,您需要按如下方式重新构建代码:
(1)在HomeController
中,首先上传图片($this->Image_upload_model->do_upload()
,然后更新您的数据库($this->homemodel->addTenants()
(2)在上传模型中,您需要调用$this->upload->data()
来获取包含文件名的信息数组(请参阅CodeIgniter文档)。然后,您必须获取该文件名并将其提供给HomeController并将其传递给addTenants
函数。
根据此指南,您应该能够相应地修改代码。
答案 2 :(得分:2)
使用$this->upload->file_name
基于system/library/upload.php
public $file_name = "";
public function data()
{
return array (
'file_name' => $this->file_name,
'file_type' => $this->file_type,
...
);
}