You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在CodeIgniter+MySQL中存储读取文件?已存无法显示求助

问题分析与修复方案

你的代码能存储文件但无法读取显示,核心问题出在查询逻辑和图片编码输出上,以下是具体问题和修复后的代码:

关键问题点

  • SQL查询变量未解析:单引号包裹的SQL语句里$imgname不会被替换为实际文件名,导致查不到对应数据。
  • base64编码未执行:你只是输出了base64_encode($row->img_data)这个字符串,没有实际调用函数生成编码后的有效内容。
  • MIME类型固定错误:硬写image/jpg,但上传的可能是png、webp等格式,会导致图片无法正常渲染。
  • 存在SQL注入风险:直接将用户输入的文件名拼入SQL语句,存在安全隐患。

修复后的代码

<?php
class File_upload extends CI_Controller
{
    public function index()
    {
        // 加载CodeIgniter文件上传类(若已在autoload.php配置可省略)
        $this->load->library('upload');

        // 输出上传表单
        echo '<head>
                <title>上传图片到数据库</title>
              </head>
              <body>
                <form method="post" enctype="multipart/form-data">
                  <input type="file" name="upload" accept=".png,.gif,.jpg,.webp" required/>
                  <input type="submit" name="submit" value="上传图片"/>
                </form>';

        if ($this->input->post('submit')) {
            // 配置文件上传验证规则
            $config['allowed_types'] = 'png|gif|jpg|jpeg|webp';
            $config['max_size']      = 2048; // 限制文件最大2MB
            $this->upload->initialize($config);

            if ($this->upload->do_upload('upload')) {
                // 获取上传文件的完整信息
                $upload_info = $this->upload->data();
                $file_content = file_get_contents($upload_info['full_path']);
                
                // 准备插入数据库的数据
                $insert_data = [
                    'img_name' => $upload_info['file_name'],
                    'img_data' => $file_content,
                    'img_mime' => $upload_info['file_type'] // 新增存储MIME类型的字段,需在数据库表中添加
                ];
                $this->db->insert('images', $insert_data);

                // 安全查询已上传的图片(用Active Record避免SQL注入)
                $this->db->where('img_name', $upload_info['file_name']);
                $query = $this->db->get('images');

                if ($query->num_rows() > 0) {
                    foreach ($query->result() as $row) {
                        // 正确执行base64编码并输出图片标签
                        $base64_content = base64_encode($row->img_data);
                        echo "<img src='data:{$row->img_mime};base64,{$base64_content}' height='100' width='100'/>";
                    }
                }
            } else {
                // 输出上传失败的错误信息
                echo $this->upload->display_errors();
            }
        }
        echo '</body>';
    }
}
?>

额外注意事项

  1. 数据库表修改:需要在images表中新增img_mime字段(建议类型为VARCHAR(255)),用于存储文件的MIME类型,保证不同格式图片都能正确显示。
  2. 安全规范:使用CodeIgniter的上传类自动验证文件类型、大小,比直接操作$_FILES更可靠;用Active Record查询避免SQL注入风险。

内容的提问来源于stack exchange,提问作者Social media

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 00:41:13