简体   繁体   中英

how to store and retrieve images in database using CodeIgniter

I am using a WAMP server, and I want to upload images in the database using CI.The image variable in database is of blob datatype. My question's as follows:

1) How to store the image instead of the file name and what datatypes should I use?

2) How to retrieve images from the DB?

My controller's code:

<?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;
}   
}
?>

My model's code:

<?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;
    }
}
}
?>

And finally here's the code for my view:

<?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; ?>

I tried solving it in different ways and searched for my problem but I didn't find any appropriate answer.

DO NOT STORE FILES INSIDE THE DATABASE!!!

This is always a bad design idea. Store the files in the file system and simply store the file names and point to the file, it will save you a lot of headaches in the future.

// 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).'">';
}

In your template:

<?php getImage(12); ?> 

where 12 is row id.

try this code

models code

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;
}

controller code

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);  
}

view

<?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; ?>

Here's a quick something I use for small PNG thumbnails. These are stored in a table called "coreg" in a field named "IMAGE". The field-type is LONGBLOB. Every upload overwrites the previous image. In the actual app the view-file is displayed as an iframe:

VIEW FILE FOR UPLOADING (better to use the CI specific form tags of course, but you get the idea)

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>

CONTROLLER TO SHOW THE IMAGE

More elegant would be to use a view instead of the echo and to move the DB logic into the model, but this shows the functionality better IMHO:

media.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'];
            }   
        }


    }

CONTROLLER TO UPLOAD THE 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);  

    }

try this code controller:-

<?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);    
            }
        }   
}

view:

<?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>
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM