代码之家  ›  专栏  ›  技术社区  ›  Razvan Zamfir

在Codeigniter 3中上载时,如何显示不允许的文件类型错误?

  •  0
  • Razvan Zamfir  · 技术社区  · 6 年前

    我正在做一个基本的工作 blog application 具有 引导4 .

    当然,这些帖子都有主要的图片。有一个 默认图像 如果用户没有上传图像,但是 上传了,有 只允许3种类型

    帖子 控制器:

    // Upload image
    $config['upload_path'] = './assets/img/posts';
    $config['allowed_types'] = 'jpg|jpeg|png';
    $config['max_size'] = '2048';
    
    $this->load->library('upload', $config);
    
    if(!$this->upload->do_upload()){
    
        $data['uerrors'] = $this->upload->display_errors();
    
        if ($data['uerrors']) {
            $this->load->view('partials/header', $data);
            $this->load->view('dashboard/create-post');
            $this->load->view('partials/footer');
        } else {
            $post_image = 'default.jpg';
        }
    
    } else {
        $data = array('upload_data' => $this->upload->data());
        $post_image = $_FILES['userfile']['name'];
    }
    

    <?php foreach ($uerrors as $uerror): ?>
      <span><?php echo $uerror; ?></span>
    <?php endforeach; ?>
    

    然而,我得到了一个 错误。

    这是整个 create()

    public function create() {
    
        // Only logged in users can create posts
        if (!$this->session->userdata('is_logged_in')) {
            redirect('login');
        }
    
        $data = $this->get_data();
        $data['tagline'] = "Add New Post";
    
        if ($data['categories']) {
            foreach ($data['categories'] as &$category) {
                $category->posts_count = $this->Posts_model->count_posts_in_category($category->id);
            }
        }
    
        $this->form_validation->set_rules('title', 'Title', 'required');
        $this->form_validation->set_rules('desc', 'Short description', 'required');
        $this->form_validation->set_rules('body', 'Body', 'required');
        $this->form_validation->set_error_delimiters('<p class="error-message">', '</p>');
    
        if($this->form_validation->run() === FALSE){
            $this->load->view('partials/header', $data);
            $this->load->view('dashboard/create-post');
            $this->load->view('partials/footer');
        } else {
            // Create slug (from title)
            $slug = url_title(convert_accented_characters($this->input->post('title')), 'dash', TRUE);
            $slugcount = $this->Posts_model->slug_count($slug, null);
            if ($slugcount > 0) {
                $slug = $slug."-".$slugcount;
            }
    
            // Upload image
            $config['upload_path'] = './assets/img/posts';
            $config['allowed_types'] = 'jpg|jpeg|png';
            $config['max_size'] = '2048';
    
            $this->load->library('upload', $config);
    
            if(!$this->upload->do_upload()){
    
                $data['uerrors'] = $this->upload->display_errors();
    
                if ($data['uerrors']) {
                    $this->load->view('partials/header', $data);
                    $this->load->view('dashboard/create-post');
                    $this->load->view('partials/footer');
                } else {
                    $post_image = 'default.jpg';
                }
    
            } else {
                $data = array('upload_data' => $this->upload->data());
                $post_image = $_FILES['userfile']['name'];
            }
    
            $this->Posts_model->create_post($post_image, $slug);
            $this->session->set_flashdata('post_created', 'Your post has been created');
            redirect('/');
        }
    } 
    

    我的错在哪里?

    0 回复  |  直到 6 年前
        1
  •  1
  •   ubayedtanvir    6 年前

    你的上传代码看起来不错,但你需要更新以下更改。

    1. 'dashboard/create-post' 当您传递给您的 'partials/header' 查看。你的 '仪表板/创建帖子' 视图没有得到任何上传错误消息,所以它说 'Undefined variable: uerrors'
    if(!$this->upload->do_upload()){
        $data['uerrors'] = $this->upload->display_errors();
        if ($data['uerrors']) {
            $this->load->view('partials/header', $data);
            $this->load->view('dashboard/create-post', $data);
            $this->load->view('partials/footer');
        } else {
            $post_image = 'default.jpg';
        }
    } else {
        $post_image = $this->upload->data('file_name');
    }
    
    1. 作为 CodeIgniter Documentation 如果说,'display\u errors()'返回字符串,而不是数组,则不必遍历错误。在你的脸上回音就行了 '仪表板/创建帖子'

    private function uploadFile(){
        if ($_FILES['userfile']['name'] === '') {
            return array(
                'status' => TRUE,
                'message' => 'No file selected.',
                'file_name' => 'default.jpg'
            );
        }
    
        // Upload image
        $config['upload_path'] = './assets/img/posts';
        $config['allowed_types'] = 'jpg|jpeg|png';
        $config['max_size'] = '2048';
    
        $this->load->library('upload', $config);
    
        if(!$this->upload->do_upload('userfile')){
            return array(
                'status' => FALSE,
                'message' => $this->upload->display_errors('<p class="text-danger ">', '</p>'),
                'file_name' => ''
            );
        }else{
            return array(
                'status' => TRUE,
                'message' => 'File uploaded successfully',
                'file_name' => $this->upload->data('file_name')
            );
        }
    }
    

    那么整个create方法应该如下所示-

    public function create() {
        // Only logged in users can create posts
        if (!$this->session->userdata('is_logged_in')) {
            redirect('login');
        }
    
        $data = $this->get_data();
        $data['tagline'] = "Add New Post";
    
        if ($data['categories']) {
            foreach ($data['categories'] as &$category) {
                $category->posts_count = $this->Posts_model->count_posts_in_category($category->id);
            }
        }
    
        $this->form_validation->set_rules('title', 'Title', 'required');
        $this->form_validation->set_rules('desc', 'Short description', 'required');
        $this->form_validation->set_rules('body', 'Body', 'required');
        $this->form_validation->set_error_delimiters('<p class="error-message">', '</p>');
    
        if($this->form_validation->run() === FALSE){
            $this->load->view('partials/header', $data);
            $this->load->view('dashboard/create-post');
            $this->load->view('partials/footer');
        } else {
            $upload = $this->uploadFile();
    
            if($upload['status'] === FALSE){
                $data['upload_error'] = $upload['message'];
    
                $this->load->view('partials/header', $data);
                $this->load->view('dashboard/create-post', $data);
                $this->load->view('partials/footer');
            }else{
                // Create slug (from title)
                $slug = url_title(convert_accented_characters($this->input->post('title')), 'dash', TRUE);
                $slugcount = $this->Posts_model->slug_count($slug, null);
                if ($slugcount > 0) {
                    $slug = $slug."-".$slugcount;
                }
    
                $this->Posts_model->create_post($upload['file_name'], $slug);
                $this->session->set_flashdata('post_created', 'Your post has been created');
                redirect('/');
            }
        }
    }
    

    最后将这行代码添加到 查看文件,就在文件输入按钮之后。

    <?php if(isset($upload_error)) echo $upload_error; ?>
    

    我认为一切都应该奏效。

        2
  •  1
  •   Stephen Mudere    6 年前

    我在这里学到了三样东西

    1) 没有像前面提到的那样将$数据传递给正确的视图

    在我看来

    <form action="http://localhost:8000/welcome/create" method="post" enctype="multipart/form-data">
              <input type="file" name="lname" ><br>
              <input type="submit" value="Submit">
            </form>
    

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

    上载错误的文件类型以测试此错误。您可能需要额外的长度来检测实际上载文件的文件类型。

        3
  •  1
  •   Razvan Zamfir    6 年前

    如果 通过修改 create() 这种方式:

    public function create() {
    
        // Only logged in users can create posts
        if (!$this->session->userdata('is_logged_in')) {
            redirect('login');
        }
    
        $data = $this->get_data();
        $data['tagline'] = "Add New Post";
    
        if ($data['categories']) {
            foreach ($data['categories'] as &$category) {
                $category->posts_count = $this->Posts_model->count_posts_in_category($category->id);
            }
        }
    
        $this->form_validation->set_rules('title', 'Title', 'required');
        $this->form_validation->set_rules('desc', 'Short description', 'required');
        $this->form_validation->set_rules('body', 'Body', 'required');
        $this->form_validation->set_error_delimiters('<p class="error-message">', '</p>');
    
        if($this->form_validation->run() === FALSE){
            $this->load->view('partials/header', $data);
            $this->load->view('dashboard/create-post');
            $this->load->view('partials/footer');
        } else {
            // Create slug (from title)
            $slug = url_title(convert_accented_characters($this->input->post('title')), 'dash', TRUE);
            $slugcount = $this->Posts_model->slug_count($slug, null);
            if ($slugcount > 0) {
                $slug = $slug."-".$slugcount;
            }
    
            // Upload image
            $config['upload_path'] = './assets/img/posts';
            $config['allowed_types'] = 'jpg|jpeg|png';
            $config['max_size'] = '2048';
    
            $this->load->library('upload', $config);
    
            if(!$this->upload->do_upload()){
    
                $errors = array('error' => $this->upload->display_errors());
    
                // Display upload validation errors 
                // only if a file is uploaded and there are errors
                if (empty($_FILES['userfile']['name'])) {
                    $errors = [];
                }
    
                if (empty($errors)) {
                    $post_image = 'default.jpg';
                } else {
                    $data['upload_errors'] = $errors;
                }
    
            } else {
                $data = array('upload_data' => $this->upload->data());
                $post_image = $_FILES['userfile']['name'];
            }
    
            if (empty($errors)) {
                $this->Posts_model->create_post($post_image, $slug);
                $this->session->set_flashdata('post_created', 'Your post has been created');
                redirect('/');
            } else {
                $this->load->view('partials/header', $data);
                $this->load->view('dashboard/create-post');
                $this->load->view('partials/footer');
            }
        }
    }
    

    create-post.php 我的看法是:

    <?php if(isset($upload_errors)){
       foreach ($upload_errors as $upload_error) {
        echo $upload_error;
       }
     }?>
    
        4
  •  0
  •   Lajos Arpad    6 年前

    此错误告诉您变量不存在或未初始化。看看这个代码

    $data['uerrors'] = $this->upload->display_errors();
    
    if ($data['uerrors']) {
    

    $uerrors 未初始化的某个变量(此代码中未显示)。注意,我不相信 array 指数 'uerrors' 数组

        5
  •  0
  •   Hamza AVvan    6 年前

    你的问题有点含糊。不管怎样,变量 $uerrors 什么时候能定下来 create() 方法将执行,我相信将在POST请求时执行。另外,你没有提到这是哪一部分:

    <?php foreach ($uerrors as $uerror): ?>
      <span><?php echo $uerror; ?> </span>
    <?php endforeach; ?>
    

    如果是的话 dashboard/create-post 查看然后尝试通过 $data partials/header

    我刚检查了密码点火器 View/Controller samples 我发现使用 isset() 函数调用,因此不要直接执行foreach循环,请执行以下操作:

    <? if (isset($uerrors)): ?>
        <? foreach ($uerrors as $uerror): ?>
          <span><?= $uerror; ?></span>
        <? endforeach; ?> 
    <? endif; ?> 
    
        6
  •  0
  •   Shehroz Altaf    6 年前

    $data['uerrors'] = '';
    

    或者检查前端的值是否不为空。

    前端,您可以这样做:

    <?php  if (isset($uerrors) && $uerrors != '') {
                foreach ($uerrors as $uerror) {
                    echo '<span>' . $uerror . '</span>';
                }
            } ?>
    

    您的控制器将是:

     $data = array();
            // Upload image
            $config['upload_path'] = './assets/img/posts';
            $config['allowed_types'] = 'jpg|jpeg|png';
            $config['max_size'] = '2048';
    
            $this->load->library('upload', $config);
    
            /*You need to initialize  $data['uerrors'] as null because you are using it on front end*/
            $data['uerrors'] = '';
            if (!$this->upload->do_upload('FilePath')) {
                $data['uerrors'] = $this->upload->display_errors();
                $this->load->view('partials/header', $data);
                $this->load->view('dashboard/create-post');
                $this->load->view('partials/footer');
            } else {
                if (isset($_POST{'your_file'})) {
                    /*'check your images here that you are receiving from front end'*/
                } else {
                    /*If there is no image, then default image is*/
                    $post_image = 'default.jpg';
                }
                $data = array('upload_data' => $this->upload->data());
                $post_image = $_FILES['userfile']['name'];
            }
    

    你可以在网上找到更多有用的帖子 How to upload image in CodeIgniter?