1

I want to make a codeigniter controller that can retrieve a "POST" base64 image, decode it, then save it into a local folder then having that path into my MySQL.

I am stuck at this point.

Can you please give me some references of this case?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Denny Kurniawan
  • 168
  • 1
  • 3
  • 21
  • I would really recommend you read [this thread](http://stackoverflow.com/questions/3748/storing-images-in-db-yea-or-nay) before you decide to do that. Good luck – Ruslan Abuzant Jan 11 '17 at 07:45

2 Answers2

0

The following code snippet is a copy=paste from CodeIgniter's official user documentation.

<?php

class Upload extends CI_Controller {

        public function __construct()
        {
                parent::__construct();
                $this->load->helper(array('form', 'url'));
        }

        public function index()
        {
                $this->load->view('upload_form', array('error' => ' ' ));
        }

        public function do_upload()
        {
                $config['upload_path']          = './uploads/';
                $config['allowed_types']        = 'gif|jpg|png';
                $config['max_size']             = 100;
                $config['max_width']            = 1024;
                $config['max_height']           = 768;

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

                if ( ! $this->upload->do_upload('userfile'))
                {
                        $error = array('error' => $this->upload->display_errors());

                        $this->load->view('upload_form', $error);
                }
                else
                {
                        $data = array('upload_data' => $this->upload->data());

                        $this->load->view('upload_success', $data);
                }
        }
}
?>

CodeIgniter does have built-in file upload class with very good documentation which I really suggest you give a quick look.

The one part or modification you will have to check carefully looks like this:

$config['file_name']            = 'a_'.md5(microtime()).'.jpg';

which tells codeigniter where to save the file in any local path you want, then from here you can simply save that to your database like this:

$result = $this->db->query('INSERT INTO AVATARS VALUES (NULL, 'user1', '" . $config['file_name'] . "') ');

Please notice that this is pseudo-code only and has not been tested in any production environment; yet, shall perfectly work.

Good luck

Ruslan Abuzant
  • 631
  • 6
  • 17
0

$base should have a base64 encoded image string:

$base = $_POST["profile_image"];
$filename = $_POST["file_name"];
$filename = $_POST["user_id"];
$binary = base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
$file = fopen('./Images/'.$filename, 'wb');
fwrite($file, $binary);
fclose($file);
Sander Toonen
  • 3,463
  • 35
  • 54
Manish
  • 29
  • 3