使用 codeigniter 上传和查看图像

Image upload and view with codeigniter

请有人向我解释如何上传图像并使用 codeigniter 查看它们。我尝试了很多方法,但其中 none 对我有用。任何帮助将不胜感激

您应该参考 CodeIgniter 用户指南。 File Upload in Codeigniter.

首先,您需要创建一个用于上传图片的目标文件夹。

因此,在 CodeIgniter(CI) 安装的根目录下创建一个名为“uploads”的文件夹。

现在在 CodeIgniter 的视图文件夹中创建两个视图 文件 file_view.php 和 upload_success.php。第一个文件将显示包含上传字段的完整表单,第二个文件将显示消息“已成功上传”。

File uploads require a multipart form

这里给大家举个例子,希望对你有帮助。

HTML代码。

<?php echo $error;?>
<!-- Error Message will show up here -->
<?php echo form_open_multipart( 'upload_controller/do_upload');?>
<?php echo "<input type='file' name='userfile' size='20' />"; ?>
<?php echo "<input type='submit' name='submit' value='upload' /> ";?>
<?php echo "</form>"?>

控制器代码:

            <?php
        if (!defined('BASEPATH'))
            exit('No direct script access allowed');
        class Upload_Controller extends CI_Controller
        {
            public function __construct()
            {
                parent::__construct();
            }
            public function file_view()
            {
                $this->load->view('file_view', array(
                    'error' => ' '
                ));
            }
            public function do_upload()
            {
                $config = array(
                    'upload_path' => "./uploads/",
                    'allowed_types' => "gif|jpg|png|jpeg|pdf",
                    'overwrite' => TRUE,
                    'max_size' => "2048000", // Can be set to particular file size , here it is 2 MB(2048 Kb)
                    'max_height' => "768",
                    'max_width' => "1024"
                );
                $this->load->library('upload', $config);
                if ($this->upload->do_upload()) {
                    $data = array(
                        'upload_data' => $this->upload->data()
                    );
                    $this->load->view('upload_success', $data);
                } else {
                    $error = array(
                        'error' => $this->upload->display_errors()
                    );
                    $this->load->view('file_view', $error);
                }
            }
        }
        ?>  

您的观点:

        <h3>Your file was successfully uploaded!</h3>
    <!-- Uploaded file specification will show up here -->
    <ul>
        <?php foreach ($upload_data as $item => $value):?>
            <li>
                <?php echo $item;?>:
                    <?php echo $value;?>
            </li>
            <?php endforeach; ?>
    </ul>
    <p>
        <?php echo anchor('upload_controller/file_view', 'Upload Another File!'); ?>
    </p>

检索图像:

首先,您需要将图像URL保存在数据库中。

$this->model->insert_data($upoad_data['file_name'], $upoad_data['full_path']);

$data = array('upload_data' => $this->upload->data());

$this->load->view('your_view', $data);

现在在视图中使用 $data。

<image src="<?php you should use that data to view image. >">

希望大家已经清楚上传后如何显示图片了。