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?
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
$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);
Related
I am working on codeigniter and during creation of one of the APIs I got the issue. I tried to upload the image on Server as a file, while searching on the web, I got familiar with inbuild upload class in codeigniter. Please have a look at this code. I am sending file from Android using this tutorial.
public function upload_image_post(){
$config['upload_path'] =base_url().'/uploads/';
$config['file_name'] = rand() .'.jpg';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = 10000;
$config['remove_spaces'] = TRUE;
$config['encrypt_name'] = TRUE;
// $file = $this->input->post('file');
$this->load->library('upload', $config);
// $this->upload->initialize($config);
$file=$_FILES['uploaded_file'];
// $this->upload->do_upload($file);
if($file){
$content=array(
'image_id'=>'IMG'.rand(),
'album_id'=> 'A',
'sp_id'=>'asQ',
'image_name'=>'aAA',
'status'=>1,
'tags'=>'s');
/* This is working*/
$res = $this->db->insert('ww_portfolio_images',$content);
}else{
$content=array(
'image_id'=>'IMG'.rand(),
'album_id'=> 'not file',
'sp_id'=>'asQaaaaa',
'image_name'=>'aAA',
'status'=>1,
'tags'=>'s');
/* This is not working, Thats Obvious*/
$res = $this->db->insert('ww_portfolio_images',$content);
}
// $destinationPath=APPPATH.'public/assets/uploads/ANKO.jpg';
if($this->upload->do_upload('uploaded_file')) {
$content=array(
'image_id'=>'IMG'.rand(),
'album_id'=> 'A',
'sp_id'=>'aaaaaaaaaaaaaaaaas',
'image_name'=>'aAA',
'status'=>1,
'tags'=>'s');
/* This is not working*/
$res = $this->db->insert('ww_portfolio_images',$content);
$this->response(['result' =>'Success',] , REST_Controller::HTTP_OK);
// return ($arr_image_info['full_path']);
}
else{
$content=array(
'image_id'=>'IMG'.rand(),
'album_id'=> 'A',
'sp_id'=>'asass',
'image_name'=>'aAA',
'status'=>1,
'tags'=>'s');
$res = $this->db->insert('ww_portfolio_images',$content);
/* This is working*/
$this->response(['result' => 'ERrro'] , REST_Controller::HTTP_OK);
// $this->response(['result' =>'Image error',], 433);
}
}
I can not figure out the problem I am facing here. I am receiving a file but it does not upload.
I have also tried to use $this->upload->do_upload() instead of $this->upload->do_upload('uploaded_file') and this $config['max_size'] = '10000'; instead of this $config['max_size'] = 10000; . Please help. Any help would be greatly appreciated.
Also, when this code run through web panel, it working fine.
Better if you provide some more detail for the type of error or warning that you are observing.
There could be number of reasons.
1) base_url() gives you the public URL. You have to specify the absolute or relative path to your upload folder.
2) (if you are using an Apache Server) Your Apache user don't have the write permission to the upload folder.
3) Folder path doesn't exists.
If the first one doesn't work, please check the rest of the points. Hope this help you.
Regards
Muaaz
Try using FCPATH
$config['upload_path'] = FCPATH . '/uploads/';
Or
$config['upload_path'] = './uploads/';
Then http://www.codeigniter.com/user_guide/libraries/file_uploading.html#the-controller
<?php
class Example extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper('form');
}
// Name function what every you want remember to change it on view form.
public function 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('uploaded_file')) {
// Then the success stuff
$upload_data = $this->upload->data();
echo $upload_data['file_name'];
} else {
// Errors
}
}
}
On view I would use the form helper functions form_open_multipart()
<?php echo form_open_multipart('example/upload');?>
<?php echo form_upload('uploaded_file', 'Upload');?>
<?php echo form_close();?>
check your form input in the view
My form view :
<input id="document" type="file" data-browse-label="browse" name="document" data-show-upload="false" data-show-preview="false" class="form-control file" />
other can be
permission issue for the uploads folder
if the folder does not exist you have to create it
And always try to debug the code with logs
document in the do_upload is the name of the input element in my view
if ($_FILES['document']['size'] > 0) {
$this->load->library('upload');
$config['upload_path'] = 'uploads/images';
$config['allowed_types'] = '*';
$config['max_size'] = $this->allowed_file_size;
$config['overwrite'] = false;
$config['encrypt_name'] = true;
$this->upload->initialize($config);
if (!$this->upload->do_upload('document')) {
$error = $this->upload->display_errors();
$this->session->set_flashdata('error', $error);
redirect($_SERVER["HTTP_REFERER"]);
}
$photo = $this->upload->file_name;
}
I am trying to upload image using code-igniter, but it's not possible, why I don't know. Can anyone help me?
Here is code I have tried
public function upload(){
$config['upload_path'] = "./assets/uploads/";
$config['allowed_types'] = "jpg|png|jpeg|gif";
$this->load->library("upload" , $config);
$rs = $this->upload->do_upload("userfile");
print_r($rs);
print_r($_FILES);
if(!$rs){
$error = array('error'=>$this->upload->display_errors());
$this->load->view("main_view", $error);
}
else{
$file_data = $this->upload->data(); $data['img'] = "localhost/FileUpload/assets/uploads/";
$file_data['file_name']; $this->load->view("success_msg" , $data);
}
}
I'm not able to actually test this of course, but I believe this will get you started.
public function upload() {
$name = 'something'; // set this based on your requirements, I often use random strings or user names according to the situation.
$config['upload_path'] = "assets/uploads/";
$config['allowed_types'] = "jpg|png|jpeg|gif";
$config['file_name'] = $name;
$this->load->library("upload" , $config);
$rs = $this->upload->do_upload("userfile");
print_r($rs);
print_r($_FILES);
if(!$rs) {
$error = array( 'error'=>$this->upload->display_errors() );
$this->load->view("main_view", $error);
}
else {
$file_data = $this->upload->data();
$file_name = $file_data['file_name'];
$ext = pathinfo($file_name, PATHINFO_EXTENSION); //Useful to store your name in database if/when you need to
$data = array('upload_data' => $upload_data);
$this->load->view("success_msg" , $data);
}
}
I need full code , where i could upload full image size in the database (not only image path but whole image size). Thank you in advance
To upload Images or files you use following code to your controller as
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())
{
$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);
}
}
Refferecne:Codeigniter Files upload guideline
How ever if you want to upload image using Ajax then please don't forget to knock then i will give entire codes blocks.
Thank you!
Are you trying to convert the image into bytes and save it on MYSQL database?
If yes, then try this code
<?php
$filename = "image.png";
$file = fopen($filename, "rb");
$contents = fread($file, filesize($filename));
fclose($file);
?>
I have the following code in my view:
if (isset($stockists)) {
$id = $stockists->ID;
echo form_open_multipart($system_settings['admin_folder'].'/stockists/form/'.$id);
}
else {
echo form_open_multipart($system_settings['admin_folder'].'/stockists/form/');
}
<?php echo "<input type='file' name='userfile' size='20' />"; ?>
There's lots of other text input fields in there that are sent to a database on submit. The file up loader is what I'm interested in though.
In my controller function, how can I check if a file exists in the up-loader after submit?
The following retruns false:
$image = ($_FILES['userfile']);
I need to check in a conditional statement if a file exists in the uploader. So for example:
if ($_FILES['userfile']) {
//do
}
But this method does not work.
The super global $_FILES
$_FILES['userfile'] isn't a boolean.
if (strlen($_FILES['userfile']['tmp_name']) > 0) {
// Yes, is uploaded
}
In the array, you've also error:
echo $_FILES['userfile']['error'];
CodeIgniter Approach
CodeIgniter has an upload class that can do the work for you.
CodeIgniter's File Uploading Class permits files to be uploaded. You can set various preferences, restricting the type and size of the files.
Below an example from the CodeIgniter documentation:
<?php
class Upload extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
}
function index()
{
$this->load->view('upload_form', array('error' => ' ' ));
}
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())
{
$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);
}
}
}
?>
See for full examples the documentation: CI File Upload Class
I'm making use of codeIgniter to upload files into folders in the server. Now I also want to save the data into the database, what do I need in order to get the raw data and then save it into the database?
Here's the model for saving files:
<?php
class files extends ci_Model{
function saves($filename, $filedata, $post_id){
$this->db->query("INSERT INTO tbl_files SET file_data='$filedata', filename='$filename', postid='$post_id'");
}
}
?>
Here's how I call it from the upload controller:
$filename = $data['upload_data']['file_name'];
$file_data = file_get_contents($data['upload_data']['file_name']);
$this->load->model('files');
$this->files->saves($filename, $file_data, 'ID1');
Table Structure:
file_data (LONG BLOB)
filename (VARCHAR)
Storing Path is very best method.
But if you want to try ....
It is same as in PHP or CodeIgniter ,
Better I give you the link, then writing code here: http://www.techcubetalk.com/2009/01/tutorial-on-how-to-store-images-in-mysql-blob-field/
Try it , it's work on my code`
function _save($id = null){
$config['upload_path'] = './asset/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = '1000';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if($_POST || $_FILES){
if(!$this->upload->do_upload('field_input_name')){
echo $this->upload->display_errors('<p>', '</p>');
} else {
$w = $this->upload->data();
$data = array(
'field_input_name' => $w['file_name'],
);
$this->db->insert('table_image', $data);
}
}
}
I have solved the problem by using the handy mysql_real_escape_string() like this:
$filename = $data['upload_data']['file_name'];
$file_data = mysql_real_escape_string(file_get_contents($data['upload_data']['full_path']));