【问题标题】:image doesn't display from database Codeigniter 4图像不显示从数据库 Codeigniter 4
【发布时间】:2021-07-29 02:45:52
【问题描述】:

我是使用 codigniter 的新手。我正在尝试通过使用创建页面将它们发送到数据库来显示来自 mysql 数据库的图像,您可以在其中输入标题、一些信息并选择图像,在创建项目后显示除图像之外的所有内容。一旦我打开 phpmyadmin,它就会显示图像有数据,但看起来它只是元数据,而不是实际图像本身。我已经坚持了几天了,所以我希望你们能帮助我!

在控制器中创建函数(已编辑):

    public function create(){
    $model = new ProjectModel();

    $file = $this->request->getFile('image');

    if ($this->request->getMethod() === 'post' && $this->validate([
            'title' => 'required|min_length[3]|max_length[255]',
            'info'  => 'required',
            'image' => 'uploaded[image]',
        ]))
    {
        $model->save([
            'title' => $this->request->getPost('title'),
            'slug'  => url_title($this->request->getPost('title'), '-', TRUE),
            'info'  => $this->request->getPost('info'),
            $tempfile = $file->getTempName(),
            $imgdata = file_get_contents($tempfile),
        ]);
        var_dump($imgdata);


        #echo view('project/success');
    }
    else
    {
        echo view('site/create');
    }
}

我的模特

namespace App\Models;

use CodeIgniter\Model;

class ProjectModel extends Model
{
protected $table = 'projects';

protected $allowedFields = ['title', 'slug', 'info', 'image'];

public function getProjects($slug = false)
{
    if ($slug === false)
    {
        return $this->findAll();
    }

    return $this->asArray()
            ->where(['slug' => $slug])
            ->first();
}
}

这是在您按下创建按钮后创建 div 元素的文件

<?php if (! empty($projects) && is_array($projects)) : ?>

<?php foreach ($projects as $project_item): ?>

    <div class="project-box" href="/projects/<?= esc($project_item['slug'], 'url') ?>">

        <?php echo '<img class="project-image" src="data:image/jpeg;base64,'.base64_encode($project_item['image']).'" alt="image" ">'?>

            <p class="project-name"><?=esc($project_item['title'])?></p>
            <div class="bottom-border">
                <p class="project-creator"><i class="far fa-user-circle"></i>&nbsp;<?=esc($project_item['creator'])?></p>
                    <div class="statistics">
                        <p class="project-likes"><i class="fas fa-heart"></i>&nbsp;<?=esc($project_item['likes'])?></p>
                        <p class="project-views"><i class="far fa-eye"></i>&nbsp;<?=esc($project_item['views'])?></p>
                    </div>
            </div>
    </div>
   <?php endforeach; ?> 
<?php else : ?>
   <h3>No Projects</h3>
<?php endif ?>

这是您可以在其中创建项目的创建文件

        <div class="parent">
           <?= \Config\Services::validation()->listErrors() ?>
            <form action="/site/create" method="post">
              <h1>Create Project</h1>
                <?= csrf_field() ?>
                <div class="form-group">
                    <input class="ph-title" type="input" name="title" placeholder="Title" /><br/>
                </div>
                <div class="grow-wrap">
                    <textarea class="ph-info" name="info" placeholder="Type in project info"></textarea>
                </div>

               <!-- <div class="file-input">
                    
                        <label for="file">
                            Select file
                            <p class="file-name"></p>
                        </label>
                </div> -->

                <input class="file-btn" type="file" name="image" value=""/><br/>
                <input class="create-btn" type="submit" name="submit" value="Create Project"/>
            </form>
    </div>

我做错了什么?

【问题讨论】:

    标签: php mysql database image codeigniter-4


    【解决方案1】:

    这里有一些问题。首先,您的表单已设置为上传图片,但需要将 enctype 添加到表单标签中,以便您的后端 PHP 可以接收 $_FILES 对象

    <form action="/site/create" method="post" enctype="multipart/form-data">
    

    从输入中删除 value=""...

     <input class="file-btn" type="file" name="image" />
    

    现在您已准备好接收文件 - 请参阅 https://codeigniter4.github.io/userguide/libraries/uploaded_files.html

    你的验证应该改变

    $this->validate([
        //... your other validations...
        'image' => 'uploaded[image]' // instead of required
    ]);
    

    如果你想将图像存储在你的服务器上,然后将图像的名称记录在数据库中以供以后检索:

    $imageDirectory="/path/to/where/you/store/images";
    $imageName = $file->getRandomName(); 
    $path = $this->request->getFile('image')->store($imageDirectory, $imageName);
    // path is now the full path to the image on your server.
    

    如果您想存储图像 BLOB 数据(如您的示例):

    $tempfile = $file->getTempName();
    $imgdata = file_get_contents($tempfile);
    

    那么您的插入将如下所示...

    $model->save([
                'title' => $this->request->getPost('title'),
                'slug'  => url_title($this->request->getPost('title'), '-', TRUE),
                'info'  => $this->request->getPost('info'),
                'image' => $imgdata,
            ]);
    

    【讨论】:

    • @MauriceBorrel - 我更新了我的回复,并附上了关于您的验证数组的注释
    • 谢谢!这是解决 image field is required 错误
    • @MauriceBorrel - 图片上传效果如何?
    • 还是不行,可能是我漏了什么
    • 您遇到了什么错误?你能说出事情在什么时候崩溃了吗?另外,您是想将图像 BLOB 存储在数据库中,还是将上传图像的路径存储在您的服务器上?
    猜你喜欢
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-07
    • 1970-01-01
    • 2017-08-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多