Codeigniter:如何将上传文件路径保存到数据库?

4

我正在尝试将文件路径放入数据库中,我已经上传了文件,但我不知道如何获取文件路径并将其放入数据库中?

以下是控制器:

    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class dogo extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('insert_article');
    }   
    public function index()
    {

    $this->load->view('dogo/dashboard.php');

    }
    //add new post to database including uploading image
    public function new_post()
    {

    //used for the dropdown menu (category)
    $this->load->model('dogo_cat');
    $data['categores_dropdown'] = $this->dogo_cat->get_categories();    

    //form validation
    $this->load->library('form_validation');//load the validation library

    $this->form_validation->set_rules('title', 'title of the post', 'required');
    $this->form_validation->set_rules('text', 'text of the post', 'required');
    //$this->form_validation->set_rules('image', 'image of the post', 'required');
    $this->form_validation->set_rules('category', 'category of the post', 'required');  

    //the form validation condition
    if($this->form_validation->run() == FALSE){
        //error
        //$this->view_data
        $this->load->view('dogo/new_post.php', $data);      
    }else{

        //no error in the form
        $title = $this->input->post('title');
        $text = $this->input->post('text');
        $category = $this->input->post('category');
        $publish = $this->input->post('publish');
        //$img_nw = $this->input->post('img_nw');
        //$img_nw = $this->input->post('img_nw');
        $image_file = $this->input->post('image_file');



        //uploading
        $this->load->model('upload_new_post');
        if($this->input->post('upload')){
        $this->upload_new_post->do_upload();

        //$this->insert_article->insert_new_post($title, $category, $img_nw, $text, $source, $publish);

        $data['images'] = $this->upload_new_post->get_images();

        echo "title of the post: " . $title . "<br /> and the text of the post " . $text . "<br /> and category is: " . $category . "<br /> and publish is: " .$publish . "<br /> and image: <pre>" . $do_upload ."</pre>";




            //echo $img_nw;


            $this->load->view('dogo/new_post.php', $data);              


        }



    }






    }   
}

以下是上传该文件的模型:

    <?php
class upload_new_post extends CI_Model{
    // retreive categories 
    var $file_path;
    var $file_path_url;

        function __construct() {
        parent::__construct();
            $this->file_path = realpath(APPPATH . '../post_data/images');
            $this->file_path_url = base_url().'post_data/images/';
    }

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


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

        $image_data = $this->upload->data();

        $config = array(
            'source_image' => $image_data['full_path'],
            'new_image' => $this->file_path . '/thumbs',
            'maintain_ration' => true,
            'width' => 150,
            'height' => 150
        );

        $this->load->library('image_lib', $config);
        $this->image_lib->resize();
    }

    function get_images(){
        $files = scandir($this->file_path);
        $files = array_diff($files, array('.', '..', 'thumbs'));

        $images = array();

        foreach ($files as $file){
            $images [] = array(
                'url' => $this->file_path_url . $file,
                'thumb_url' => $this->file_path_url . 'thumbs/' .$file
            );

        }
        return $images;
    }

}       

以下是插入查询的模型:

    <?php
class Insert_article extends CI_Model{

    //insert new post
    function __construct() {
        parent::__construct();
    }   

    function insert_new_post($title, $category, $img_nw, $text, $source, $publish)
    {
        $query_insert = "INSERT INTO hs_news_nw (idcat_nw, idsc_nw, idusr_nw, title_nw, img_nw, text_nw, active_nw, totalview_nw, date_nw) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $this->db->query($query_insert, array($category, $source, 1, $title, $img_nw, $text, 1, 1000, '2011-10-12 02:01:24'));
    }
}       
4个回答

1

在你的upload_new_post模型中的do_upload()函数中应返回$image_data

$image_data = $this->upload->data();
..
..
return $image_data;

$image_data 包含已上传文件的所有信息,包括文件名和路径(使用 print_r 函数来查看)。您可以将其传递到控制器中的 Insert_article 模型以存储到数据库中。

供参考:

http://codeigniter.com/user_guide/libraries/file_uploading.html


我按照您在模型中的建议添加了return $image_data,但是当我尝试测试发布的数据时,在dogo控制器中输入echo $image_data;没有返回任何数据,同时我输入了$image_data['full_path'];也没有返回任何数据。 - ahmedsaber111
这里是模型{upload_new_post},我在do_upload函数的结尾添加了return $image_data,如下所示:function do_upload(){ .. return $image_data; }然后我在控制器{dogo}中添加了以下代码:if($this->input->post('upload')){ $data['upload_img'] = $this->upload_new_post->do_upload(); $this->upload_new_post->do_upload();..当我使用print_r($data)时,我发现我想要的内容在这个数组[full_path]中,但我不知道如何将其提取出来。 - ahmedsaber111
  1. 您将以 $data['upload_img']['full_path'] 的形式检索它。
  2. 为什么要调用 do_upload() 两次?
- Vikk

1
请尝试使用$fpath查看是否给出了正确的路径:
    $config['upload_path'] = './uploads';
    $config['allowed_types'] = 'gif|jpg|jpeg|png|txt|php|pdf';
    $config['max_size']         = '9000';
    $config['encrypt_name']     = true;

    $image_data = $this->upload->data();
    $fname=$image_data[file_name];
    $fpath=$image_data[file_path].$fname;

0

如果我理解正确,你可以使用realpath来获取真实的文件位置


问题在于我无法在控制器中检索上传图像的路径,以便将其发送到数据库,能否帮忙吗?我可能会按照顺序工作不正确,请告诉我完成此过程的正确方法。 - ahmedsaber111
根据这里,您应该能够在$image_data['full_path']中找到完整的文件路径。 - user973254

0
您可以尝试使用文件处理上传。
控制器:
public function add_slide() {
    // set the page name
    $data['title_admin'] = "Add & View Slide Information";
    // load the custom file processing library
    $this->load->library('file_processing');
    $this->load->library('form_validation');

    // check if click on the submit button
    if ($this->input->post('Save')) {

        // write the validation rule
        $this->form_validation->set_rules('slide_name', 'Name', 'required');
        $this->form_validation->set_rules('slide_short_description', 'Short Description', '');
        $this->form_validation->set_rules('slide_long_description', 'Detail Description', '');
        $this->form_validation->set_rules('slide_image', 'Image', 'callback_file_validate[no.slide_image.jpg,gif,png]');
        //$this->form_validation->set_rules('slide_mission_vision', 'Diabetes Profile', 'callback_file_validate[no.slide_mission_vision.pdf]');
        // check the validation
        if ($this->form_validation->run()) {
            $addData['slide_name'] = $this->input->post('slide_name');
            $addData['slide_short_description'] = $this->input->post('slide_short_description');
            $addData['slide_long_description'] = $this->input->post('slide_long_description');
            $addData['slide_image'] = $this->file_processing->image_upload('slide_image', './images/slide/', 'size[500,1000|100,500]');
            //$addData['slide_mission_vision'] = $this->file_processing->file_upload('slide_mission_vision', './images/slide_mission_vision/', 'pdf');
            $addData['slide_add_date'] = date('Y-m-d');
            // call the crate model and inset into database
            if ($this->sa_model->save_slide_info($addData)) {
                $this->session->set_flashdata('success_msg', 'Save Information Successfully!!');
                redirect('super_admin/add_slide');
            }
            else
                $data['error_msg'] = mysql_error();
        }
    }

    // load the views
    $data['s2'] = TRUE;
    $data['slide_info'] = $this->sa_model->select_all_slide_info();
    $data['admin_main_content'] = $this->load->view('admin/add_slide', $data, true);
    $this->load->view('admin/admin_master', $data);
}

// file validation
public function file_slide_validate($fieldValue, $params) {
    // get the parameter as variable
    list($require, $fieldName, $type) = explode('.', $params);
    // get the file field name
    $filename = $_FILES[$fieldName]['name'];
    if ($filename == '' && $require == 'yes') {
        $this->form_validation->set_message('file_validate', 'The %s field is required');
        return FALSE;
    } elseif ($type != '' && $filename != '') {
        // get the extention
        $ext = strtolower(substr(strrchr($filename, '.'), 1));
        // get the type as array
        $types = explode(',', $type);
        if (!in_array($ext, $types)) {
            $this->form_validation->set_message('file_validate', 'The %s field must be ' . implode(' OR ', $types) . ' !!');
            return FALSE;
        }
    }
    else
        return TRUE;
}

模型:

  // insert new record into user table
public function save_slide_info($data) {
    $this->db->insert('tbl_slide', $data);
    return $this->db->affected_rows();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接