【问题标题】:How to File Upload in CodeIgniter如何在 CodeIgniter 中上传文件
【发布时间】:2018-01-10 01:39:48
【问题描述】:

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

到目前为止,我一直在尝试编辑我的 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; ?>

【问题讨论】:

  • 问题出在哪里?您遇到的错误是什么?尝试编辑您的问题并删除与此问题无关的代码。
  • 我在这个网站上看到了很多你的问题,每个问题都显示出与上一个相同的努力,并且质量没有明显的改进:某某不起作用,这是我所有代码的转储...请尝试解决更多问题,然后返回一个简洁的问题和相关代码。

标签: php codeigniter file-upload codeigniter-3


【解决方案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')

【讨论】:

    【解决方案2】:

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

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

    第三,你需要用你的配置初始化上传库! $this-&gt;load-&gt;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');
    

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

    &lt;?php echo form_upload('post_image' , array('class' =&gt; 'form-control')); ?&gt; 并使用用户文件删除输入

    【讨论】:

      猜你喜欢
      • 2015-04-18
      • 1970-01-01
      • 2017-08-04
      • 2016-08-05
      • 1970-01-01
      • 1970-01-01
      • 2017-11-27
      • 1970-01-01
      • 2020-08-17
      相关资源
      最近更新 更多