在Codeigniter中使用图像上传的注册表单

时间:2016-03-01 15:31:24

标签: php forms codeigniter

我有一个用户注册表单,它工作正常,但想在其中添加图片上传功能。这基本上就是我想要实现的目标

ScreenShot 1 Screenshot 1

ScreenShot 2 screenshot 2

到目前为止,这就是我所做的

控制器:

class Employees extends CI_Controller {
var $pgToLoad;

public function __construct() {
    parent::__construct();
    #this will start the session
    session_start();
    $this->load->helper(array('form', 'url'));


    if(!isset($_SESSION['userId']) || !isset($_SESSION['userLevel']) || !isset($_SESSION['employeeid']) || !isset($_SESSION['firstname']) || !isset($_SESSION['lastname'])) {
        redirect('home', 'location');
    }

    #this will load the model
    $this->load->model('Contents');

    #get last uri segment to determine which content to load
    $continue = true;
    $i = 0;
    do {
        $i++;
        if ($this->uri->segment($i) != "") $this->pgToLoad = $this->uri->segment($i);
        else $continue = false;             
    } while ($continue);        
}

public function index() {       
    $this->main();
}   

public function main() {
    #set default content to load 
    $this->pgToLoad = empty($this->pgToLoad) ? "employees" : $this->pgToLoad;
    $disMsg = "";

    #this will delete the record selected
    if($this->uri->segment(2) == 'delete') { 
        $this->deleteRecord();
    }

    #this will check if the post value is trigger
    if(isset($_POST['addnew'])) {
        $this->addRecord(); 
    }                   

    #this will check if the post value is trigger
    if(isset($_POST['saveinfo'])) {
        $this->updateinfo();    
    }           

    if($this->uri->segment(2) == 'add' || $this->uri->segment(2) == 'edit') {
        #this display the form for products
        $this->displayForm();
    } else {
        #this will display the job orders
        $this->getAllEmployees();       
    }   


    if($this->uri->segment(2) == 'print') {
        #this display the form for products
        $this->pdf();
    } 

if($this->uri->segment(2) == 'do_upload') {
        #this display the form for products
        $this->do_upload();
    } 

    #this will logout the user and redirect to the page
    if($this->uri->segment(2) == 'logout') {
        session_destroy();
        redirect('home', 'location');
    }                   

    $data = array ( 'pageTitle' => 'Payroll System | ADMINISTRATION',
                    'disMsg'    => $disMsg,                                             
                    'mainCont'  => $this->mainCont );

    $this->load->view('mainTpl', $data, FALSE);
}


function do_upload(){

    if($this->input->post('upload')){

        $config['upload_path'] = './uploads/';
        $config['allowed_types'] = 'gif|jpg|png';
        $config['max_size']    = '1024';
        $config['max_width']  = '1024';
        $config['max_height']  = '768';
        $this->load->library('upload', $config);

        if ( ! $this->upload->do_upload()){

        $error = array('error' => $this->upload->display_errors());
        $this->load->view('pages/employeesform', $error);
        }

        else{

        $data=$this->upload->data();
        $this->thumb($data);
        $file=array(
        'img_name'=>$data['raw_name'],
        'thumb_name'=>$data['raw_name'].'_thumb',
        'ext'=>$data['file_ext'],
        'upload_date'=>time()
        );
        $this->Contents->add_image($file);
        $data = array('upload_data' => $this->upload->data());
        $this->load->view('pages/upload_success', $data);
        }
    }

    else{

    redirect(site_url('employees'));

    }

}

function thumb($data){

    $config['image_library'] = 'gd2';
    $config['source_image'] =$data['full_path'];
    $config['create_thumb'] = TRUE;
    $config['maintain_ratio'] = TRUE;
    $config['width'] = 275;
    $config['height'] = 250;
    $this->load->library('image_lib', $config);
    $this->image_lib->resize();

}
    public function displayForm() {
    $data['level'] = $this->Contents->exeGetUserLevel();
    $data['status'] = $this->Contents->exeGetUserStatus();

    $data['employee'] = $this->Contents->exeGetEmpToEdit($_SESSION['userId']);      
    if($this->uri->segment(2) == 'edit') { 
        $data['employee'] = $this->Contents->exeGetEmpToEdit($_SESSION['userId']);
        $data['emp'] = $this->Contents->exeGetEmpToEdit($this->uri->segment(3));
        $data['info'] = $this->Contents->exeGetUserInfo($this->uri->segment(3));    
        $this->mainCont = $this->load->view('pages/employeesform', $data, TRUE);
    }                   
    $this->mainCont = $this->load->view('pages/employeesform', $data, TRUE);                
}

#this will add new record
public function addRecord() {
    if(empty($_POST['fname']) || empty($_POST['mname']) || empty($_POST['lname']) || empty($_POST['empass']) || empty($_POST['emailadd']) || empty($_POST['gender']) || empty($_POST['datehired']) || empty($_POST['salary'])) {    
        $disMsg = "Please fill up the form completely.";
        $_SESSION['disMsg'] = $disMsg;  
    } else {
        $addNew = $this->Contents->exeAddNewRecord();

        if($addNew['affRows'] > 0) {
            $_SESSION['disMsg'] = "New Employee has been added.";
            redirect('employees', 'location');          
        } else {
            $disMsg = "Unable to add new employee.";
        }       
    }           
}

查看:

 <?php echo form_open_multipart('employees/do_upload');?>

            <img id="preview" style = "width: 200px; height: 200px;">
            <input type="file" name = "userfile" id="input">

            <br /><br />

            <input type="submit" value="upload" name="upload" />

            </form>


<form action="" method="post" enctype="multipart/form-data" id="empform" role="form" name="empform">
            <div class="box-body">
                <div class="row">
                    <div class="col-lg-6">
                        <div class="input-field col s12">
                            <label>Firstname</label>
                            <input type="text" id="fname" name="fname" class="form-control" value="<?php if(!empty($_POST['fname'])) { echo $_POST['fname']; } elseif(!empty($emp[0]['firstname'])) { echo $emp[0]['firstname']; } ?>">
                        </div>
                        <div class="input-field col s12">
                            <label>Middle Name</label>
                            <input type="text" id="mname" name="mname" class="form-control" value="<?php if(!empty($_POST['mname'])) { echo $_POST['mname']; } elseif(!empty($emp[0]['middlename'])) { echo $emp[0]['middlename']; } ?>">
                        </div>
                        <div class="input-field col s12">
                            <label>Password</label>
                            <input type="password" id="empass" name="empass" class="form-control" value="<?php if(!empty($_POST['empass'])) { echo $_POST['empass']; } ?>">
                        </div>
                        <div class="input-field col s12">
                            <label>Employee ID</label>
                            <input type="text" id="empno" name="empno" class="form-control" value="<?php if(!empty($_POST['empno'])) { echo $_POST['empno']; } elseif(!empty($emp[0]['employeeid'])) { echo $emp[0]['employeeid']; } ?>">
                        </div>
                    </div>
                        <div class="col-lg-4" style="padding-left:0;">
                            <?php if($this->uri->segment(2) == "edit") { ?>
                            <button type="submit" name="saveinfo" class="btn btn-lg btn-primary btn-block">Save</button>
                            <?php } else { ?>
                            <button type="submit" name="addnew" class="btn btn-lg btn-primary btn-block">Save</button>
                            <?php } ?>

                        </div>
                    </div>
                </div>
            </form>

正如您在视图中看到的,有两种形式。第一种形式是图像上传,另一种是用户注册表。一旦点击保存按钮,我如何能够在注册表单中包含图像上传并执行图像上传,保存用户信息和表单验证?

1 个答案:

答案 0 :(得分:4)

这就是我使用表单处理文件上传的方式......它是一个通用示例,但它应该有所帮助。

视图

<?php echo form_open_multipart('someController/someFunction') ?>

    <div class="form-group">
        <label for="name">Name</label>
        <input type="text" name="name">
    </div>

    <div class="form-group">
        <label for="uploads">Upload a file</label>
        <input name="uploads[]" id="fileupload" type="file" multiple="true">
    </div>

    <input type="submit">

<?php echo form_close() ?>

控制器

public function addRecordToTable()
{
    $this->form_validation->set_rules('name' , 'Name', 'required');

    if ($this->form_validation->run() == true) {
        $array = array(
            'name'      => $this->input->post('name')
        );

        $record_id = $this->some_model->addData('some_table', $array);
        $this->uploadFiles($record_id);
    }
}

public function uploadFiles($record_id)
{
    $config = array(
        'upload_path'   => FCPATH . "path\to\directory",
        'allowed_types' => 'jpg|png|jpeg',
        'overwrite'     => TRUE,                       
    );

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

    $files = $_FILES['uploads'];

    foreach ($files['name'] as $key => $filename) {
        $_FILES['uploads[]']['name']     = $files['name'][$key];
        $_FILES['uploads[]']['type']     = $files['type'][$key];
        $_FILES['uploads[]']['tmp_name'] = $files['tmp_name'][$key];
        $_FILES['uploads[]']['error']    = $files['error'][$key];
        $_FILES['uploads[]']['size']     = $files['size'][$key];

        $config['file_name'] = $filename;

        $this->upload->initialize($config);

        if (isset($_FILES['uploads[]']['name']) && !empty($_FILES['uploads[]']['name'])) {
            if ( ! $this->upload->do_upload('uploads[]')) {
                $error = array('error' => $this->upload->display_errors());

            } else {
                $uploads[] = $this->upload->data();
                $array = array(
                    'record_id' => $record_id,
                    'filename'  => $_FILES['uploads[]']['name'],
                    'size'      => $_FILES['uploads[]']['size']
                );
                $this->some_model->addData('uploads', $array);
            }
        }
    }
    redirect(base_url() . 'someController/someFunction/' . $record_id);
}

模型

public function addData($table, $array)
{
    $this->db->insert($table, $array);

    return $this->db->insert_id();
}

修改

根据您的评论,要将数据插入多个表,只需修改控制器中的代码即可:

public function submitEmployeeDetails()
{
    $this->form_validation->set_rules('value1' , 'Value 1', 'required');
    $this->form_validation->set_rules('value2' , 'Value 2', 'required');

    if ($this->form_validation->run() == true) {
        $array1 = array(
            'value1' => $this->input->post('value1')
        );

        $array2 = array(
            'value2' => $this->input->post('value2')
        );           

        $this->your_model->addData('employees', $array1);
        $this->your_model->addData('employees_details', $array2);
    }
}

所以你有两个数组,你在模型中调用addData()函数,第一个参数指定表的名称,第二个参数传递要添加的关联数组。