为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
拉丁的传说 2022-07-16 10:07:53
我正在使用Codeigniter 3.1.8和Bootstrap 4开发一个基本的博客应用程序。当然,这些帖子有主要图像。如果用户没有上传图像,则有默认图像,但如果上传图像,则只允许 3 种类型:jpg、jpeg 和 png。想要警告用户以防她/他尝试上传其他文件格式,我在Posts控制器中执行了此操作:// 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; ?>然而,我得到一个未定义的变量:uerrors错误。这是整个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');    }     我的错误在哪里?
查看完整描述

3 回答

?
慕桂英4014372

TA贡献1871条经验 获得超13个赞

通过修改这种方式,我已成功显示上传错误(如果尝试上传,否则使用默认图像):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;

   }

 }?>


查看完整回答
反对 回复 2022-07-16
?
jeck猫

TA贡献1909条经验 获得超7个赞

我在这里捡到了三样东西


1) 如前所述,没有将 $data 传递给正确的视图


2) 在视图上期望数组而不是字符串,即错误的数据类型


3) 最后函数 do_upload() 需要参数字符串 $field。缺少这就是为什么您只有 no upload selected 错误。如果设置了这个参数,codeigniter 真的会抛出错误的文件类型错误。我这样做是为了测试


在我看来


<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")){

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


查看完整回答
反对 回复 2022-07-16
?
慕码人2483693

TA贡献1860条经验 获得超9个赞

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


将数据传递给您的'dashboard/create-post'视图,就像您传递给您的'partials/header'视图一样。您的'dashboard/create-post'视图没有收到任何上传错误消息,所以它说'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');

}

正如CodeIgniter 文档所说,'display_errors()' 返回字符串,而不是数组,您不必遍历错误。只是在你的'dashboard/create-post'观点上呼应它。

为了您的方便,请以不同的方法制作您的上传任务,以便您也可以在更新方法中重新使用它。例如——


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')

        );

    }

}

然后你的整个创建方法应该是这样的 -


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('/');

        }

    }

}

最后在您的视图文件中添加这行代码'dashboard/create-post',就在文件输入按钮之后。


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

我认为一切都应该工作。


查看完整回答
反对 回复 2022-07-16
  • 3 回答
  • 0 关注
  • 94 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信