无法在代码编写器中显示视图页上的文件错误信息


unable to show file error message on the view page in codeigniter

我试图使用flashdata显示图像上传错误消息,但我下面显示的代码不能正常工作。原因是什么呢?

请给我一个解决这个问题的方法。

mycontrollerPage.php

class Booksetups extends CI_Controller  
{
    function book($book_id = 0)
    {
       $config = array(); 
       $config['base_url'] = 'http://localhost/thexxr.com/Booksetups/book/pgn/';
       $config["total_rows"] = $this->Booksmodel->record_count(); 
       $config['uri_segment'] = 4; 
       $config['per_page'] = 5;  
       $config['full_tag_open'] = '<div id="pagination">';
       $config['full_tag_close'] = '</div>';
        //------------not wroking file upload error validation------------------------------------------   
        $config['upload_path'] = 'uploads/'; 
        $config['allowed_types'] = 'gif|jpg|jpeg|png'; 
        $config['max_size'] = '1000'; 
        $config['max_width'] = '1920'; 
        $config['max_height'] = '1280'; 
        $config['remove_spaces'] = 'TRUE'; 
        $config['file_path'] = 'TRUE'; 
        $config['full_path']    = '/uploads/';
        $this->load->library('upload', $config);
        $this->upload->do_upload("img1");
        $this->upload->do_upload("img2");
        //------------------------------------------------------------------------

       $this->pagination->initialize($config);   
       $page = ($this->uri->segment(4)) ? $this->uri->segment(4) : 0;   
       $this->form_validation->set_error_delimiters('<div  class="error">', '</div>')->set_rules('subject_id', 'subject_id','trim|required|min_length[1]|max_length[150]|xss_clean');
       $this->form_validation->set_error_delimiters('<div  class="error">', '</div>')->set_rules('cover_id', 'cover_id','trim|required|min_length[1]|max_length[150]|xss_clean');
       $this->form_validation->set_error_delimiters('<div  class="error">', '</div>')->set_rules('language_id', 'language_id','trim|required|min_length[1]|max_length[150]|xss_clean');
       $this->form_validation->set_error_delimiters('<div  class="error">', '</div>')->set_rules('edition_id', 'edition_id','trim|required|min_length[1]|max_length[150]|xss_clean');
        if(($this->input->post('book_id'))&& ($this->form_validation->run() === TRUE))
        {  
            if( ! $this->upload->do_upload()) //trying to display error
            {
                   $error = array('error' => $this->upload->display_errors()); 
                   $this->session->set_flashdata('error', $error);
                   redirect(current_url()); 
            }
            $this->session->set_flashdata('msg', '1 row(s) affected.');
            $this->Booksmodel->entry_update();  
            redirect(current_url());
        }
    }
}       

Myview.php

<?php echo '<fieldset><legend>'. $formtopic.'</legend>' ?>  
<?php echo validation_errors();  ?>   
<?php 
    $message = $this->session->flashdata('msg');  
    if($message)
    {
    ?>
    <div class="success" id="msgdiv"><?php echo  $this->session->flashdata('msg'); ?></div> 
    <?php 
    }
?>  
<?php 
$message = $this->session->flashdata('error');  
    if($message)
    {
    ?> 
    <?php echo $error;?>   
    <!-- Here i am getting. Message like "array" why not i am getting the error message instead? --> 
<?php 
    }
?> 

我建议使用form_validation的validation_errors()。我是这样做的。
看看这个答案中的库吧。
这个库有两个方法validate_upload(它只检查文件是否有效)
和do_upload(必须仅在validate_upload返回true时使用)。

Codeigniter中有一个文件上传库,下面是文档。复制我的答案的代码,并将其粘贴到一个名为MY_Upload.php的文件中,并将该文件保存在application/code文件夹中。现在我定义一个像这样的规则

$this->form_validation->set_rules('userfile', 'New Image', 'trim|callback_valid_upload');   

当图片上传是可选的,你可以将它包裹在一个条件

if(isset($_FILES['userfile']) AND $_FILES['userfile']['name']!= ''){
    $this->form_validation->set_rules('userfile', 'New Image', 'trim|callback_valid_upload');   
}   

其中userfile是表单的文件字段。你可以看到我在规则callback_valid_upload
中调用了一个函数这是在回调

中使用的控制器方法
public function valid_upload()
{
    $this->load->library('upload'); 
    $config['upload_path']      =   'your path here';           
    $config['allowed_types']    =   'png';
    $config['max_size']         =   2048;
    $config['max_width']        =   85;
    $config['max_height']       =   110;
    $this->upload->initialize($config);
    if (!$this->upload->validate_upload('userfile'))
    {
        $this->form_validation->set_message('valid_upload', $this->upload->display_errors());
        return FALSE;
    }else{
        return TRUE;
    }       
}

这个方法将检查我们上传的文件是否有效,如果成功则返回true,否则返回false。
当验证失败时,加载表单

View
echo validation_errors();
//blah blah
//<form action="">
//  <input type="" />
//  <input type="" />
//  <input type="" />
//</form>

如果你想单独显示消息

<input type="file" name="userfile" id="" /> 
<?php echo form_error('userfile')?>

如果验证成功,现在像这样上传文件。

if($this->form_validation->run())
{
    if(isset($_FILES['userfile']) AND $_FILES['userfile']['name'] !='')
    {
        $this->upload->do_upload('userfile'); // this will upload file
        $image_data =   $this->upload->data();
        $data['image_field_name_of_table']      =   $image_data['raw_name'];
    }
    //other data in $data array here
    $id =   $this->mymodel->insert($data);
    if($id){
        $this->session->set_flashdata('notice', ' Successful');
        redirect('your url');   
    }
}else{
    //load view here
}    

更多编辑:
我注意到你的代码有一个问题

   $config = array(); 
   $config['base_url'] = 'http://localhost/thexxr.com/Booksetups/book/pgn/';
   $config["total_rows"] = $this->Booksmodel->record_count(); 
   $config['uri_segment'] = 4; 
   $config['per_page'] = 5;  
   $config['full_tag_open'] = '<div id="pagination">';
   $config['full_tag_close'] = '</div>';
    $this->load->library('upload', $config);
    $this->upload->do_upload("img1");
    unset($config);
    $config['upload_path'] = 'uploads/'; 
    $config['allowed_types'] = 'gif|jpg|jpeg|png'; 
    $config['max_size'] = '1000'; 
    $config['max_width'] = '1920'; 
    $config['max_height'] = '1280'; 
    $config['remove_spaces'] = 'TRUE'; 
    $config['file_path'] = 'TRUE'; 
    $config['full_path']    = '/uploads/';
    $this->load->library('upload', $config); //load again with new configuration
    $this->upload->do_upload("img1");
    $this->upload->do_upload("img2");   

下面是一些用来设置和显示CI中的错误的辅助函数

if (!function_exists('set_flash_message'))
{
    function set_flash_message($title, $message, $type='success')
    {
        $CI =& get_instance();
        $CI->session->set_flashdata(
            'flash_message',
            array(
                'type' => $type,
                'title' => $title,
                'text' => $message));
    }
}
if (!function_exists('flash_message'))
{
    function flash_message()
    {
        $CI =& get_instance();
        $message = $CI->session->flashdata('flash_message');
        return $CI->load->view('desktop/flash_message', $message, TRUE);
    }
}

你可以设置来自控制器的消息:

set_flash_message('Error', 'Something went wrong', 'error');

和显示错误从视图

<?php echo flash_message(); ?>

正如我在评论中所说;

您正在获取数组,因为您正在设置flash错误消息作为一个数组[$error = array('error' => $this->upload->display_errors());],尝试将其设置为一个字符串

如果您查看源代码中的函数,它要么接受散列数组,要么接受字符串。
如果传递了一个数组,那么它会将带有键的flashdata设置为flash消息类型,带有值的message;忽略第二个参数。
如果你以字符串的形式传递两个参数,它将用第一个字符串设置flashdata键。

所以要么做;

$this->session->set_flashdata('error', 'something went wrong');

$this->session->set_flashdata(array('error', 'something went wrong'));

源代码:

function set_flashdata($newdata = array(), $newval = '')
    {
        if (is_string($newdata))
        {
            $newdata = array($newdata => $newval);
        }
        if (count($newdata) > 0)
        {
            foreach ($newdata as $key => $val)
            {
                $flashdata_key = $this->flashdata_key.':new:'.$key;
                $this->set_userdata($flashdata_key, $val);
            }
        }
    }