codeIgniter表单验证无法使用文件上载选项

时间:2015-08-18 11:33:41

标签: codeigniter codeigniter-2 codeigniter-form-helper

我正在尝试此代码,但它无法使用文件上传。 当没有文件上传字段时,它工作正常但文件上传不起作用。

请帮帮我。

form.php的

<?php echo validation_errors(); ?>  

<?php echo form_open_multipart('emp'); ?>

    <form name="ajaxform" id="ajaxform" action="<?php echo base_url().'/emp/operation'?>" method="POST" enctype="multipart/form-data"> 
        <table border="1">
            <tr> 
                <th>Name</th> 
                <td><input type="text" name="name" value="<?php echo $name; ?>" size="50"/></td> 
            </tr> 
            <tr> 
                <th>Email </th> 
                <td><input type="text" name="email" value="<?php echo $email; ?>"/></td> 
            </tr> 
            <tr> 
                <th>Address</th> 
                <td><input type="text" name="address" value="<?php echo $address; ?>" /></td> 
            </tr> 
            <tr> 
                <th>Phone</th> 
                <td><input type="text" name="phone" value="<?php echo $phone; ?>" /></td> 
            </tr>
            <tr> 
                <th>Photo</th> 
                <td><input type="file" name="userfile" /></td> 
            </tr>              
        </table>
        <input type="hidden" name="id" value="<?php echo $id; ?>" /> 
        <input type="hidden" id="btn" value="<?php echo $submit; ?>" name="btn"/> 
        <input type="submit" id="simple-post" value="<?php echo $submit; ?>" name="simple-post"/> 
    </form> 
</body> 

这是控制器代码。 Emp.php

  public function index(){
        $this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');

        $this->form_validation->set_rules('name', 'Name','required','callback_username_check');
        $this->form_validation->set_rules('email', 'Email', 'required|is_unique[registration.email]');
        $this->form_validation->set_rules('address', 'Address', 'required');
        $this->form_validation->set_rules('phone', 'Phone', 'required');
        if (empty($_FILES['userfile']['name']))
        {
            $this->form_validation->set_rules('userfile', 'Photo', 'required');
        }

        $config['upload_path'] = './uploads/';
        $config['allowed_types'] = 'gif|jpg|png';
        $config['max_size'] = '1800';
        $config['max_width']  = '1924';
        $config['max_height']  = '1924';
        $new_name = time().$_FILES['userfile']['name'];
        $config['file_name'] = $new_name;

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

        if ( ! $this->upload->do_upload() OR $this->form_validation->run() == FALSE)
        {
            $error = array('error' => $this->upload->display_errors());
            $this->load->view('form', $error);
        }
        else
        {
            $data = array('upload_data' => $this->upload->data());           
            $this->emp_model->add_data();
            $query['value']=$this->GetAll(); 
        }
}

2 个答案:

答案 0 :(得分:0)

试试这个

if (null != ($_FILES['userfile']['tmp_name']))
{
  $this->form_validation->set_rules('userfile', 'Photo', 'callback_checkPostedFiles');
}

此功能用于验证

public function checkPostedFiles()
    {
        $file_name = trim(basename(stripslashes($_FILES['userfile']['name'])), ".\x00..\x20");
        $file_name = str_replace(" ", "", $file_name);
         if (isset($_FILES['userfile']) && !empty($file_name)) {
            $allowedExts = array("jpeg", "jpg", "png"); // use as per your requirement
            $extension = end(explode(".", $file_name));
            if (in_array($extension, $allowedExts)) {
                 return true;
            } else {
                $this->form_validation->set_message('checkPostedFiles', "You can upload jpg or png image only");
                return false;
            }
         } else {
             $this->form_validation->set_message('checkPostedFiles', "You must upload an image!");
             return false;
         }
    }

答案 1 :(得分:0)

检查此示例代码以进行图片上传:

表格:

<form method="post" action="" id="upload_file">
                    <div class="modal-body">
                            <div class="box-body">                                         
                                  <div class="form-group">
                                        <label for="exampleInputFile">Profile Picture</label>
                                        <input type="file" id="userfile" accept="image/*" name="userfile">
                                        <p class="help-block">Requested size : 215*215</p>
                                    </div>

                           </div>        
                    </div>

                    <div class="modal-footer">
                            <div class="btn-group">
                                    <button type="button" class="btn btn-default md-close" data-dismiss="modal">Close</button>                                       
                                    <input type="submit" class="btn btn-primary" name="submit" value="Save Changes">
                            </div>
                    </div>
                    </form>  

在您的视图中加入此js

表格提交的Js

$(function() {
    $('#upload_file').submit(function(e) {

        e.preventDefault();
        $.ajaxFileUpload({
        url:'<?php echo base_url(); ?>profile/upload_file', 
        type: "POST",
        fileElementId :'userfile',         

        success: function() {
    alert("file uploaded!");
     }
         });
    return false;
    });
});

在控制器中

$userid = $session_data['id'];

$file_element_name = 'userfile';    

$pathToUpload = '/var/www/html/uploads/' . $userid;

if ( ! file_exists($pathToUpload) )
{
$create = mkdir($pathToUpload, 0777);

if (!$create)
return;
}


$config['upload_path']   = $pathToUpload;
$config['allowed_types'] = 'gif|jpg|png';


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

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

$this->upload->display_errors();
}
else
{
$data = $this->upload->data();
//$this->user->insert_file($data['file_name'], $userid);
$data = array(

'userPhoto' => $data['file_name']

);


$this->db->where('user_id', $userid);
$this->db->update('tbl_user_profile', $data); 

}
//@unlink($_FILES[$file_element_name]);
相关问题