如何在CodeIgniter中上传文件

时间:2018-01-10 01:39:49

标签: php codeigniter file-upload codeigniter-3

所以我在我的博客页面工作,我决定创建一个输入,将图像上传到我资产文件夹中的文件夹。

到目前为止,我一直在尝试编辑我的Post_controller,这是我到目前为止所做的:

public function add()
{
    // Field Rules
    $this->form_validation->set_rules('title', 'Title', 'trim|required|min_length[3]');
    $this->form_validation->set_rules('subject_id', 'Subject', 'trim|required');
    $this->form_validation->set_rules('body', 'Body', 'trim|required');
    $this->form_validation->set_rules('is_published', 'Publish', 'required');
    $this->form_validation->set_rules('is_featured', 'Feature', 'required');
    $this->form_validation->set_rules('order', 'Order', 'integer');

    if ($this->form_validation->run() == FALSE) {
        $subject_options = array();
        $subject_options[0] = 'Select Post Category';

        $subject_list = $this->Posts_categories_model->get_list();

        foreach ($subject_list as $subject) {
            $subject_options[$subject->id] = $subject->title;
        }

        $data['subject_options'] = $subject_options;

        // Load template
        $this->template->load('admin', 'default', 'posts/add', $data);
    } else {
        $slug = str_replace(' ', '-', $this->input->post('title'));
        $slug = strtolower($slug);

        // Page Data
        $data = array(
            'title'         => $this->input->post('title'),
            'slug'          => $slug,
            'subject_id'    => $this->input->post('subject_id'),
            'body'          => $this->input->post('body'),
            'is_published' => $this->input->post('is_published'),
            'is_featured'  => $this->input->post('is_featured'),
            'in_menu'      => $this->input->post('in_menu'),
            'user_id'      => $this->session->userdata('user_id'),
            'order'        => $this->input->post('order'),
            'post_image'    => $this->upload->do_upload($this->input->post('post_image')),
        );

        // Upload Image
          $data['upload_path'] = './assets/img/posts';
          $data['allowed_types'] = 'gif|jpg|png';
          $data['max_size'] = '2048';
          $data['max_width'] = '2000';
          $data['max_height'] = '2000';

      if(!$this->upload->do_upload($this->input->post('post_image'))){
          $this->input->post('post_image') = './assets/img/posts/noimage.jpg';
      } else {
          $data = array('upload_data' => $this->upload->data());
          $this->input->post('post_image') = $_FILES['userfile']['name'];
      }

        // Insert Page
        $this->Post_model->add($data);

        // Activity Array
        $data = array(
            'resource_id' => $this->db->insert_id(),
            'type'        => 'post',
            'action'      => 'added',
            'user_id'     => $this->session->userdata('user_id'),
            'message'     => 'A new post was added (' . $data["title"] . ')'
        );

        // Insert Activity
        $this->Activity_model->add($data);

        // Set Message
        $this->session->set_flashdata('success', 'Post has been added');

        // Redirect
        redirect('admin/posts');
    }
}

正如您所看到的,我创建了一个post_image值,该值应该将文件上传到文件夹中,但我无法使其正常工作,有人可以帮助我吗?

这是我创建帖子的视图:

<h2 class="page-header">Add Post</h2>
<?php echo validation_errors('<p class="alert alert-danger">'); ?>
<?php echo form_open_multipart('admin/posts/add'); ?>
    <!-- Page Title -->
    <div class="form-group">
        <?php echo form_label('Post Title', 'title'); ?>
        <?php
            $data = array(
                'name' => 'title',
                'id'    => 'title',
                'maxlength' => '100',
                'class'     => 'form-control',
                'value'     => set_value('title')
            );
        ?>
        <?php echo form_input($data); ?>
    </div>

    <!-- Page Img -->
    <div class="form-group">  
        <?php echo form_label('Upload Image', 'post_image') ?>
        <?php form_upload('post_image' , array('class' => 'form-control')); ?>
        <input type="file" name="userfile" size="20">
    </div>

    <!-- Page Subject -->
    <div class="form-group">
        <?php echo form_label('Post Category', 'subject_id'); ?>
        <?php echo form_dropdown('subject_id', $subject_options, 0, array('class' => 'form-control')); ?>
    </div>

    <!-- Page Body -->
    <div class="form-group">
        <?php echo form_label('Body', 'body'); ?>
        <?php
            $data = array(
                'name'          => 'body',
                'id'            => 'body',
                'class'         => 'form-control',
                'value'         => set_value('subject')
            );
        ?>
        <?php echo form_textarea($data); ?>
    </div>

    <!-- Publish -->
    <div class="form-group">
        <?php echo form_label('Published', 'is_published'); ?>
        <?php echo form_radio('is_published', 1, TRUE); ?> Yes 
        <?php echo form_radio('is_published', 0, FALSE); ?> No
    </div>

    <!-- Feature -->
    <div class="form-group">
        <?php echo form_label('Feature', 'is_featured'); ?>
        <?php echo form_radio('is_featured', 1, FALSE); ?> Yes 
        <?php echo form_radio('is_featured', 0, TRUE); ?> No
    </div>

    <!-- Menu -->
    <div class="form-group">
        <?php echo form_label('Add To Menu', 'in_menu'); ?>
        <?php echo form_radio('in_menu', 1, TRUE); ?> Yes 
        <?php echo form_radio('in_menu', 0, FALSE); ?> No
    </div>

    <!-- Order -->
    <div class="form-group">
        <?php echo form_label('Order', 'order'); ?>
        <input class="form-control" name="order" id="order" type="number">
    </div>

    <?php echo form_submit('mysubmit', 'Add Post', array('class' => 'btn btn-primary')); ?>
<?php echo form_close(); ?>
<script>
/*TinyMce editor*/
    tinymce.init({
    selector: "textarea",
    theme: "modern",
    image_advtab: true,    
    plugins: [
         "advlist autolink link image lists charmap  preview hr anchor pagebreak spellchecker",
         "searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime  nonbreaking",
         "table contextmenu directionality template paste textcolor"
            ],
    toolbar: "insertfile undo redo | styleselect | bold underline italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | image link | code fullscreen"
     });
</script>

这是我想要显示它们的索引页面:

<?php if($posts) : ?>
    <?php foreach($posts as $page) : ?>
        <div class="featured-page">
            <a href="<?php echo base_url(); ?>posts/show/<?php echo $page->slug; ?>" class="thumbnail"><h2 class="page-header"><?php echo $page->title; ?></h2></a>
            <!-- Post Image -->
            <img src="<?php echo base_url(); ?>assets/img/posts/<?php echo $page->post_image; ?>">
            <a href="<?php echo base_url(); ?>posts_categories/posts/<?php echo $page->subject_id; ?>"><h2 class="page-header"><?php echo 'Category'; ?></h2></a>
            <?php echo word_limiter($page->body,45); ?>
            <p><a class="btn btn-default" href="<?php echo base_url(); ?>posts/show/<?php echo $page->slug; ?>">Read More</a></p>
        </div>
    <?php endforeach; ?>
    <?php else : ?>
    <div class="alert alert-danger">No Post Found</div>
<?php endif; ?>

2 个答案:

答案 0 :(得分:1)

您没有在视图文件中回显表单上传。

在form_upload方法中添加ECHO。

<?php echo form_upload('post_image' , array('class' => 'form-control')); ?>

并删除html文件上传,因为你不需要它

<input type="file" name="userfile" size="20">

在您的CONTROLLER上验证表格上传时,只需说出

即可
$this->upload->do_upload('post_image')

答案 1 :(得分:0)

首先,do_upload需要输入文件的名称

其次,通常在你的代码中你正在做$this->input->post('post_image')这将返回 nothing ,因为图像或文件位于$_FILES数组而不是$_POST数组中

第三,您需要使用您的配置初始化上传库! $this->load->library('upload', $someconfig)

所以这毕竟你的代码应该是这样的:

        $slug = str_replace(' ', '-', $this->input->post('title'));
        $slug = strtolower($slug);

        // Upload Image
        $upload['upload_path'] = './assets/img/posts';
        $upload['allowed_types'] = 'gif|jpg|png';
        $upload['max_size'] = '2048';
        $upload['max_width'] = '2000';
        $upload['max_height'] = '2000';

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

        if (!$this->upload->do_upload('post_image')) {
            // in view you do this:  base_url()/assets/img/posts/ no need for full string here just filename
            $filename = 'noimage.jpg';
            // or leave blank and sort it out in your view with empty($page->post_image) ? 'noimage.jpg' : $page->post_image (better approach)
        } else {
            $upload_data = $this->upload->data();
            $filename = $upload_data['file_name'];
        }

        // Page Data
        $data = array(
            'title' => $this->input->post('title'),
            'slug' => $slug,
            'subject_id' => $this->input->post('subject_id'),
            'body' => $this->input->post('body'),
            'is_published' => $this->input->post('is_published'),
            'is_featured' => $this->input->post('is_featured'),
            'in_menu' => $this->input->post('in_menu'),
            'user_id' => $this->session->userdata('user_id'),
            'order' => $this->input->post('order'),
            'post_image' => $filename
        );

        // Insert Page
        $this->Post_model->add($data);

        // Activity Array
        $data = array(
            'resource_id' => $this->db->insert_id(),
            'type' => 'post',
            'action' => 'added',
            'user_id' => $this->session->userdata('user_id'),
            'message' => 'A new post was added (' . $data["title"] . ')'
        );

        // Insert Activity
        $this->Activity_model->add($data);

        // Set Message
        $this->session->set_flashdata('success', 'Post has been added');

        // Redirect
        redirect('admin/posts');

另外请考虑其他回答者的说明,它们对于回复您的文件输入是有效的。

<?php echo form_upload('post_image' , array('class' => 'form-control')); ?>并使用userfile删除输入