【问题标题】:how to store and retrieve images in database using CodeIgniter如何使用 CodeIgniter 在数据库中存储和检索图像
【发布时间】:2013-06-17 22:02:07
【问题描述】:

我正在使用 WAMP 服务器,我想使用 CI 将图像上传到数据库中。数据库中的图像变量是 blob 数据类型。我的问题如下:

1)如何存储图像而不是文件名以及我应该使用哪些数据类型?

2) 如何从数据库中检索图像?

我的控制器代码:

<?php class Image_control extends CI_Controller{
function index()
{
    //$this->load->view('image_view');

    //$this->Image_model->do_upload();

    $data['images']=$this->Image_model->get_images();
    $this->load->view('image_view',$data);  
}
function do_upload()
{
    $config = array(
        'allowed_types' => 'jpg|png|bmp', 
        'upload_path'=>'./images1/',
        'max_size'=>2000
    );
    $this->load->library('upload',$config);
    if (!$this->upload->do_upload()) {
        $errors[]=array('error'=>$this->upload->display_errors());
        $this->load->view('image_view',$errors);
    }
    $image_path=$this->upload->data();
    $file_name=$image_path['file_name'];
    $config = array(
        'a_name' => $this->input->post('a_name'),
        'a_details'=>$this->input->post('a_info'),
        'a_photo'=>$file_name
    );
    $insert=$this->db->insert('animalstore',$config);
    return $insert;
}   
}
?>

我的模型代码:

<?php class Image_model extends CI_Model {
function get_images()
{
    $query = $this->db->get('animalstore');
    if($query->num_rows > 0 )
    {
        foreach($query->result() as $rows)
        {
            $data[] = $rows;
        }
        return $data;
    }
}
}
?>

最后是我的观点的代码:

<?php
    echo form_open_multipart('image_control/do_upload');
    echo form_input('a_name','Animal Name');
    echo form_input('a_info','Animal Information');
    echo form_upload('userfile');
    echo form_submit('upload','Upload');
    echo form_close();
?>

<?php foreach ($images as $image):?>
<h1><?php echo $image->a_name;?></h1>
<h1><?php echo $image->a_details;?></h1>
<img src = "/<?php// echo ltrim($image->a_photo, '/'); ?>" >
<img src="http://localhost/ci_test/images1/<?php echo $image->a_photo;?>"/> 
<img src="<?php //echo sprintf("images/%s", $image['screenshot']);?>" />
<h1><?php// echo $image->a_photo;?></h1>
<?php endforeach; ?>

我尝试以不同的方式解决它并搜索我的问题,但我没有找到任何合适的答案。

【问题讨论】:

标签: php mysql html codeigniter


【解决方案1】:

不要在数据库中存储文件!!!

这总是一个糟糕的设计理念。将文件存储在文件系统中,简单存储文件名和指向文件,以后会省去很多麻烦。

【讨论】:

  • 我不同意,当服务器在集群上时会发生什么?备份发生了什么?对于我来说,最好的设计方法是将图像存储在数据库中。
  • -1 用于提供意见而不是添加解决方案。例如,可移植性是将图像(或其他文件)存储在数据库中的众多优势之一。
【解决方案2】:
// uploading
public function do_upload(){
...

$image_path=$this->upload->data();
$uploaded_image = $image_path['full_path'];

// Read the file
$fp = fopen($uploaded_image, 'r');
$data = fread($fp, filesize($uploaded_image));
$data = addslashes($data);
fclose($fp);

// here you can easy insert $data to 'a_photo' column.    

}


// Viewing, $image_id is row id
public function getImage($image_id){

// select $row from database as usual and then

$content = $row['a_photo'];
echo '<img src="data:image/jpeg;base64,'.base64_encode($content).'">';
}

在您的模板中:

<?php getImage(12); ?> 

其中 12 是行 ID。

【讨论】:

  • 为什么要在模板/视图中调用控制器方法?
  • 这只是一个展示它如何工作的例子。在现实世界中 getImage() 将在控制器中调用,结果分配给某个模板变量,然后显示在模板中。而在现实世界中,TravisO 的回答是完全正确的 :)
【解决方案3】:

试试这个代码

型号代码

function do_upload() {

    $config = array(
            'allowed_types' => 'jpg|png|bmp', 
            'upload_path'=>'./images1/', //make sure you have this folder
            'max_size'=>2000
        );

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

        if ($this->upload->do_upload()) {
            echo "Upload success!";
        } else {
            echo "Upload failed!";
        }
    $image_data = $this->upload->data();

    }  

function get_images()
    {
        $query = $this->db->get('animalstore');
        return $query;
    }

function Save_gallery($in)
{
$save=$this->db->insert('animalstore',$in);
return $save;
}

控制器代码

function index()
{
    $this->load->model('Image_control'); //call a models

    if ($this->input->post('upload')) {

    $in=array();

    $in['a_name']    = $this->input->post('a_name'),
    $in['a_details'] = $this->input->post('a_info'),
    $in['a_photo']=$_FILES['userfile']['name'];

    if($this->Image_model->do_upload()) {

    echo $this->upload->display_errors();

    }else {

    $this->Image_model->Save_gallery($in);

    header('location:index');
    }

    $data['images']=$this->Image_model->get_images();
    $this->load->view('image_view',$data);  
}

查看

<?php
    echo form_open_multipart('image_control/index');
    echo form_input('a_name','Animal Name');
    echo form_input('a_info','Animal Information');
    echo form_upload('userfile');
    echo form_submit('upload','Upload');
    echo form_close();
?>

<?php foreach ($images as $image):?>
<h1><?php echo $image['a_name'];?></h1>
<h1><?php echo $image['a_details'];?></h1>
<?php echo '<img src ="'. base_url().'images1/'.$image['a_photo'].'" >";
endforeach; ?>

【讨论】:

  • 没有将其存储在数据库中
【解决方案4】:

这是我用于小型 PNG 缩略图的快速方法。 这些存储在名为“IMAGE”的字段中的名为“coreg”的表中。字段类型为 LONGBLOB。每次上传都会覆盖以前的图像。在实际应用中,视图文件显示为 iframe:

查看文件上传(当然最好使用 CI 特定的表单标签,但你明白了)

add_image.php:

    Current image:
   <img src='/media/png/coreg/<?=$coregID?>' />
    <? if(isset($error)){ echo $error; }?>
    <form method='post' enctype="multipart/form-data" action='add_image/<?=$coregID?>'>
      <input name="userfile" type="file"  class='vLink' />
      <input name="submitbtn" type="submit" value=" upload &amp; overwrite " class='eLink' />
    </form>

控制器显示图像

更优雅的是使用视图而不是回显并将数据库逻辑移动到模型中,但这更好地显示了功能恕我直言:

媒体.php

    require_once dirname(__FILE__) . "/base.php";

        class Media extends BaseController {

        function __construct() {  
            parent::__construct();
        }


        function png($table,$id)  {
             $this->db->where('ID',$id);
            $r = $this->db->get($table);
            if($r->num_rows){
                $r = $r->result_array();
                header("Content-Type: image/png"); 
                echo $r[0]['IMAGE'];
            }   
        }


    }

上传图像的控制器:

function add_image($coregID){
        $data['coregID'] = $coregID;
        $data['error'] = '';
        if(isset($_POST['submitbtn'])){
            $config['upload_path'] = './assets/img/coreg/';
            $config['allowed_types'] = 'png';
            $config['max_size'] = '100';
            $config['max_width']    = '350';
            $config['max_height']  = '350';
            $config['file_name']    = $coregID.".png";
            if(file_exists($config['upload_path'].$config['file_name'])){
                unlink($config['upload_path'].$config['file_name']);
            }
            $this->load->library('upload', $config);

            if ( ! $this->upload->do_upload()){             
                $data['error'] = $this->upload->display_errors();   
            }   else    {
                $this->upload->data();
                // now move the image into the DB
                $fp = fopen($config['upload_path'].$config['file_name'], 'r');
                $data = fread($fp, filesize($config['upload_path'].$config['file_name']));

                $this->db->where('ID',$coregID);
                $this->db->update('COREG',array('IMAGE' =>$data));
                fclose($fp);
                // optionally delete the file from the HD after this step
                //unlink($config['upload_path'].$config['file_name']);
            }
        }

            $this->load->view("add_image", $data);  

    }

【讨论】:

    【解决方案5】:

    试试这个代码 控制器:-

    <?php
    class Profile extends CI_Controller {
            public function __construct()
            {
                    parent::__construct();
                    $this->load->helper(array('form', 'url'));
            }
    
            public function index()
            {
                    $this->load->view('profile', array('error' => ' ' ));
            }
    
            function do_upload(){
                $config['upload_path']          = './uploads/';
                $config['allowed_types']        = 'gif|jpg|png';
                $this->load->library('upload', $config);
                if ( ! $this->upload->do_upload())
                {
                        $error = array('error' => $this->upload->display_errors());
    
                        $this->load->view('profile', $error);
                }
                else
                {
                        $data = $this->upload->data();
                        $data['img']=base_url().'./uploads/'.$data['file_name'];
                        $image['profile_pic'] = $data['file_name'];
                        $this->db->insert('user_profile_pic', $image);
                        $this->load->view('profile', $data);    
                }
            }   
    }
    

    【讨论】:

    • 嗨,请解释一下您的解决方案的作用以及它与其他答案的不同之处。
    【解决方案6】:

    查看:

    <?php echo form_open_multipart('profile/do_upload');?>
    <input type="file" name="userfile" size="20" />
    <br /><br /> 
    <input type="submit" value="upload" />
    <img src="<?php echo $img ?>" width="300px" height="300px">
    </form>
    ?>
    

    【讨论】:

      猜你喜欢
      • 2011-03-21
      • 1970-01-01
      • 2010-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-27
      • 1970-01-01
      • 2011-02-16
      相关资源
      最近更新 更多