Foreach loop not working in codeigniter model and controller both - codeigniter

My simple foreach loop is working damn weird, please help me to solve this
here are my codes of controller
public function index()
{
$this->load->model('file_list');
$query = 'SELECT * FROM `files_data` WHERE file_extension = "jpg" and size > 0 LIMIT 0,10';
foreach($this->db->query($query)->result() as $file){
$data['check'] = $this->file_list->preview_maker($file->file_id, $file->file_full_path, $file->file_extension);
}
//$this->load->view('viewtest', $data);
//$this->home_footer();
}
and here is model
public function preview_maker($file_id, $file_full_path, $extension){
if(file_exists('preview/'.$file_id.'.jpg')){
$preview = 'preview/'.$file_id.'.jpg';
} else {
if($extension == 'jpg' || $extension == 'gif' || $extension == 'png'){
$config = array(
'source_image' => 'stuff'.$file_full_path, //get original image
'new_image' => 'preview/'.$file_id.'.jpg', //save as new image //need to create thumbs first
'maintain_ratio' => true,
'width' => 80,
'height' => 80
);
$this->load->library('image_lib', $config); //load library
$this->image_lib->resize(); //do whatever specified in config
$preview = '/preview/'.$file_id.'.jpg';
} elseif ($extension == 'mp3'){
$preview = '/preview/music.jpg';
} elseif ($extension == 'apk'){
$preview = '/preview/android.jpg';
} elseif ($extension == 'jar'){
$preview = '/preview/java.png';
} elseif ($extension == 'zip'){
$preview = '/preview/zip.jpg';
} elseif ($extension == '3gp' || $extension == 'mp4' || $extension == 'avi'){
$preview = '/preview/movie.png';
}
}
return $preview;
}
The problem is, foreach loop is not working continious, its working for 1 record only for each refresh, then next record next refresh

as #prix was trying to tell you,
foreach($this->db->query($query)->result() as $file){
$data['check'] = $this->file_list->preview_maker($file->file_id, $file->file_full_path, $file->file_extension);
}
should read
foreach($this->db->query($query)->result() as $file){
$data['check'][] = $this->file_list->preview_maker($file->file_id, $file->file_full_path, $file->file_extension);
}
otherwise you just keep writing over the top of your value.
Also, read up on http://php.net/manual/en/control-structures.switch.php

Actually this thing worked for me...
i had problem about generating thumb
$config = array(
'source_image' => 'stuff'.$file_full_path, //get original image
'new_image' => 'preview/'.$file_id.'.jpg', //save as new image //need to create thumbs first
'maintain_ratio' => true,
'width' => 80,
'height' => 80
);
$this->image_lib->initialize($config);
$resize = $this->image_lib->resize();
$this->image_lib->clear(); //do whatever specified in config
$preview = '/preview/'.$file_id.'.jpg';
i didnt use
$this->image_lib->clear();
last time

Related

Image resize in codeigniter

I want to upload multiple images using two file input as well as resize them.
1. original image
2. 100 x 100
3. 400 x 200
All works fine but image lib not resize properly.It uploads images in original size.I have check following things.
1. Image lib load only once. which i load in __construct().
2. before initializing clear the image lib. $this->image_lib->clear();
function do_upload($name,$shop_code) {
$files = $_FILES;
if ($name == 'pre_photo_array') {
$photo_name = 'pre_photo_array';
} else {
$photo_name = 'post_photo_array';
}
$cpt = count($_FILES[$name]['name']);
--$cpt;
for ($i = 0; $i < $cpt; $i++) {
$_FILES[$photo_name]['name'] = $files[$photo_name]['name'][$i];
$_FILES[$photo_name]['type'] = $files[$photo_name]['type'][$i];
$_FILES[$photo_name]['tmp_name'] = $files[$photo_name]['tmp_name'][$i];
$_FILES[$photo_name]['error'] = $files[$photo_name]['error'][$i];
$_FILES[$photo_name]['size'] = $files[$photo_name]['size'][$i];
if ($photo_name == 'pre_photo_array') {
$config['upload_path'] = './assets/images/shop_images/pre_pic/';
} else {
$config['upload_path'] = './assets/images/shop_images/post_pic/';
}
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['overwrite'] = FALSE;
$config['file_name'] = $shop_code.'_'.time();
$this->upload->initialize($config);
if (!$this->upload->do_upload($photo_name)) {
$error = array('error' => $this->upload->display_errors());
$file_path[] = ' ';
} else {
$upload_data = $this->upload->data();
if ($name == 'pre_photo_array') {
$imgdata=exif_read_data('assets/images/shop_images/pre_pic/'.$upload_data['file_name'], 'IFD0');
$source_image_path = getimagesize('assets/images/shop_images/pre_pic/'.$upload_data['file_name']);
$source_image = 'assets/images/shop_images/pre_pic/'.$upload_data['file_name'];
$Pre_Thumbnail_new_image = 'assets/images/shop_images/pre_pic/Thumbnail/'.$upload_data['file_name'];
$Pre_ppt_new_image = 'assets/images/shop_images/pre_pic/PPT/'.$upload_data['file_name'];
} else {
$imgdata=exif_read_data('assets/images/shop_images/post_pic/'.$upload_data['file_name'], 'IFD0');
$source_image_path = getimagesize('assets/images/shop_images/post_pic/'.$upload_data['file_name']);
$source_image = 'assets/images/shop_images/post_pic/'.$upload_data['file_name'];
$Post_Thumbnail_new_image = 'assets/images/shop_images/post_pic/Thumbnail/'.$upload_data['file_name'];
$Post_ppt_new_image = 'assets/images/shop_images/post_pic/PPT/'.$upload_data['file_name'];
}
$rotation_angle = 0;
switch(isset($imgdata['Orientation'])) {
case 3:
$rotation_angle='180';
break;
case 6:
$rotation_angle='90';
break;
case 8:
$rotation_angle='90';
break;
}
if($name == 'pre_photo_array') {
$Thumbnail_new_image = $Pre_Thumbnail_new_image;
$ppt_new_image = $Pre_ppt_new_image;
} else {
$Thumbnail_new_image = $Post_Thumbnail_new_image;
$ppt_new_image = $Post_ppt_new_image;
}
// Create Thumbnail
$Thumbnail['image_library'] = 'gd2';
$Thumbnail['source_image'] = $source_image;
$Thumbnail['new_image'] = $Thumbnail_new_image;
$Thumbnail['create_thumb'] = TRUE;
$Thumbnail['thumb_marker'] = FALSE;
$Thumbnail['maintain_ratio'] = TRUE;
$Thumbnail['width'] = 100;
$Thumbnail['height'] = 100;
$Thumbnail['rotation_angle'] = $rotation_angle;
$this->image_lib->clear();
$this->image_lib->initialize($Thumbnail);
// resize image
$this->image_lib->resize();
$this->image_lib->rotate();
// handle if there is any problem
if(!$this->image_lib->resize()) {
echo "if";
echo $this->image_lib->display_errors();exit;
}
if($source_image_path[0] > $source_image_path[1]){
$width = 400;
$height = 200;
}else{
$width = 200;
$height = 400;
}
// Create PPt image
$ppt['image_library'] = 'gd2';
$ppt['source_image'] = $source_image;
$ppt['new_image'] = $ppt_new_image;
$ppt['create_thumb'] = FALSE;
$ppt['thumb_marker'] = FALSE;
$ppt['maintain_ratio'] = TRUE;
$ppt['width'] = 400;
$ppt['height'] = 200;
$ppt['rotation_angle']=$rotation_angle;
$this->image_lib->clear();
$this->image_lib->initialize($ppt);
// resize image
$this->image_lib->resize();
$this->image_lib->rotate();
// handle if there is any problem
if(!$this->image_lib->resize()) {
echo $this->image_lib->display_errors();exit;
}
if($photo_name == 'pre_photo_array') {
$path = 'assets/images/shop_images/pre_pic/';
} else {
$path = 'assets/images/shop_images/post_pic/';
}
$file_path[] = $path.$upload_data['file_name'];
}
}
return $file_path;
}
}
I am adding my Upload Image and Create Multiple Thumbnail Sizes in CodeIgniter Example. Hope it helps you.
//initialize the path where you want to save your images
function __construct(){
parent::__construct();
//return the full path of the directory
//make sure these directories have read and write permessions
$this->original_path = realpath(APPPATH.'../uploads/original');
$this->resized_path = realpath(APPPATH.'../uploads/resized');
$this->thumbs_path = realpath(APPPATH.'../uploads/thumbs');
}
function do_upload(){
$this->load->library('image_lib');
$config = array(
'allowed_types' => 'jpg|jpeg|gif|png', //only accept these file types
'max_size' => 2048, //2MB max
'upload_path' => $this->original_path //upload directory
);
$this->load->library('upload', $config);
$image_data = $this->upload->data(); //upload the image
//your desired config for the resize() function
$config = array(
'source_image' => $image_data['full_path'], //path to the uploaded image
'new_image' => $this->resized_path, //path to
'maintain_ratio' => true,
'width' => 128,
'height' => 128
);
//this is the magic line that enables you generate multiple thumbnails
//you have to call the initialize() function each time you call the resize()
//otherwise it will not work and only generate one thumbnail
$this->image_lib->initialize($config);
$this->image_lib->resize();
$this->image_lib->clear();
$config = array(
'source_image' => $image_data['full_path'],
'new_image' => $this->thumbs_path,
'maintain_ratio' => true,
'width' => 36,
'height' => 36
);
//here is the second thumbnail, notice the call for the initialize() function again
$this->image_lib->initialize($config);
$this->image_lib->resize();
$this->image_lib->clear();
}

how to do image upload in codeigniter?

I am trying to upload an image in root folder and its file name in database. here is what I did for the upload function:
public function add_blog($id=0){
if(!empty($_FILES['picture']['name'])){
$config['upload_path'] = 'uploads/blog_image';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['file_name'] = $_FILES['picture']['name'];
//Load upload library and initialize configuration
$this->load->library('upload',$config);
$this->upload->initialize($config);
// print_r($value['name'][$s]);exit;
if($this->upload->do_upload('picture')){
$uploadData = $this->upload->data();
$picture = $uploadData['file_name'];
print_r($picture); exit;
}
}
print_r($config['file_name']); exit;
$data['blog_data']=array('blog_post'=>$this->input->post('blog_post'),
'posted_by'=>$this->input->post('posted_by'),
'blog_image'=>$picture);
if ($id==0){
$this->db->insert('blog',$data['blog_data']);
// $last_id = $this->db->insert_id();
}
else {
$this->db->where('id',$id);
// $last_id = $this->db->insert_id();
$this->db->update('blog',$data['blog_data']);
}
}
problem here is i am being able to insert other data except image. I get the image name with that print_r($config[file_name]) if i do print_r() and exit, if not it will just insert other data except image. But the image is neither uploaded in root folder nor its name in database. If I give the non existing upload path, then also its not throwing any error. I think code inside If is not executed. How can i solve this ? Thanks in advance.
private function _upload_image( ) {
$this->load->library( 'upload' );
if ($_FILES && $_FILES['picture']['name'] !== ""){
$config['upload_path'] = 'uploads/blog_image';
$config['allowed_types'] = 'jpg|jpeg|png|bmp';
$config['max_size'] = 10000;
/*the picture name must be unique, use function now()*/
$config['file_name'] = $_FILES['picture']['name'] . now();
$config['file_ext_tolower'] = TRUE;
$this->upload->initialize( $config );
if ( $this->upload->do_upload( 'picture' ) ){
$file_name = $this->upload->data()['file_name'];
$full_path = $this->upload->data()['full_path'];
/*If you want create a thumb, use this part*/
$this->load->library('image_lib');
$config = array(
'source_image' => $path,
'new_image' => $this->_image_path,
'maintain_ratio' => true,
'width' => 128,
'height' => 128,
'create_thumb' => TRUE,
'thumb_marker' => '_thumb',
);
$this->image_lib->initialize( $config );
$this->image_lib->resize();
/*Save in database*/
$this->db->insert('blog', [
'file_name' => $file_name,
'full_path' => $full_path
]);
} else {
//if picture is empty, do something
}
}
}
You do not need to use $_FILES && $_FILES ['picture']['name']! == "" only if your form has the picture field as an optional field, $this->upload->do_upload('picture') and get data from $this->upload->data(), read the manual
public function add_blog()
{
$config['upload_path'] = '.uploads/blog_image';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['max_size'] = 10000;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('picture'))
{//Do something with errors
$errors = $this->upload->display_errors();
}
else
{
$data = $this->upload->data();
$this->db->insert('blog', [
'file_name' => $data['file_name'],
'full_path' => $data['full_path']
]);
}
}
I just didn't mention the file size to be uploaded. I did this in my above code and worked.
EDIT
public function add_blog($id=0){
if(!empty($_FILES['picture']['name'])){
$config['upload_path'] = 'uploads/blog_image';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['max_size'] = 0;
$config['file_name'] = $_FILES['picture']['name'];
//Load upload library and initialize configuration
$this->load->library('upload',$config);
$this->upload->initialize($config);
// print_r($value['name'][$s]);exit;
if($this->upload->do_upload('picture')){
$uploadData = $this->upload->data();
$picture = $uploadData['file_name'];
// print_r($picture); exit;
}
}
// print_r($config['file_name']); exit;
$data['blog_data']=array('blog_post'=>$this->input->post('blog_post'),
'posted_by'=>$this->input->post('posted_by'),
'blog_image'=>$picture);
if ($id==0){
$this->db->insert('blog',$data['blog_data']);
// $last_id = $this->db->insert_id();
}
else {
$this->db->where('id',$id);
// $last_id = $this->db->insert_id();
$this->db->update('blog',$data['blog_data']);
}
}
And this code works for both insert and update.

error column 'picture' cannot be null

My initial question was posted wrong so i'm reposting it. I am practicing with a tutorial on tutsplus by joost van veen and i added an image upload to the controller but every time i try to save a post i get an error from database saying column 'picture' cannot be null. I've checked other answers but nothing explains the problem. Any help would be appreciated.
MY CONTROLLER
public function edit($post_id = NULL) {
// Fetch all articles or set a new one
if ($post_id) {
$this->data['article'] = $this->article_m->get($post_id);
count($this->data['article']) || $this->data['errors'][] = 'article could not be found';
}
else {
$this->data['article'] = $this->article_m->get_new();
}
// Set up the form
$rules = $this->article_m->rules;
$this->form_validation->set_rules($rules);
if ($this->input->post('userSubmit')) {
//check if user uploads picture
if (!empty($_FILES['picture']['name'])) {
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'jpg|png|gif|jpeg';
$config['file_name'] = $_FILES['picture']['name'];
//load upload library and initialize configuration
$this->upload->initialize($config);
if ($this->upload->do_upload('picture')) {
$uploadData = $this->upload->data();
$picture = $uploadData['file_name'];
} else {
$picture = '';
}
} else {
$picture = '';
}
// prepare array of posts data
$data = $this->article_m->array_from_post(array(
'title',
'slug',
'content',
'category_id',
'picture',
'pubdate'
));
$insertPosts = $this->article_m->save($data, $post_id);
redirect('admin/article');
//storing insertion status message
if ($insertPosts) {
$this->session->set_flashdata('success_msg', 'Post has been added Successfully.');
} else {
$this->session->set_flashdata('error_msg', 'error occured while trying upload, please try again.');
}
}
// Load view
$this->data['subview'] = 'admin/article/edit';
$this->load->view('admin/components/page_head', $this->data);
$this->load->view('admin/_layout_main', $this->data);
$this->load->view('admin/components/page_tail');
}
MY_MODEL
public function array_from_post($fields) {
$data = array();
foreach ($fields as $field) {
$data[$field] = $this->input->post($field);
$data['category_id'] = $this->input->post('category');
}
return $data;
}
public function save($data, $id = NULL) {
// Set timestamps
if ($this->_timestamps == TRUE) {
$now = date('Y-m-d H:i:s');
$id || $data['created'] = $now;
$data['modified'] = $now;
}
// Insert
if ($id === NULL) {
!isset($data[$this->_primary_key]) || $data[$this->_primary_key] = NULL;
$this->db->set($data);
$this->db->insert($this->_table_name);
$id = $this->db->insert_id();
}
// Update
else {
$filter = $this->_primary_filter;
$id = $filter($id);
$this->db->set($data);
$this->db->where($this->_primary_key, $id);
$this->db->update($this->_table_name);
}
return $id;
}
RULES TO SET FORM VALIDATION
public $rules = array(
'pubdate' => array(
'field' => 'pubdate',
'label' => 'Publication date',
'rules' => 'trim|required|exact_length[10]'
),
'title' => array(
'field' => 'title',
'label' => 'Title',
'rules' => 'trim|required|max_length[100]'
),
'slug' => array(
'field' => 'slug',
'label' => 'Slug',
'rules' => 'trim|required|max_length[100]|url_title'
),
'content' => array(
'field' => 'content',
'label' => 'Content',
'rules' => 'trim|required'
),
'picture' => array(
'field' => 'picture',
'label' => 'Upload File',
'rules' => 'trim'
),
);
public function get_new() {
$article = new stdClass();
$article->title = '';
$article->category_id = '';
$article->slug = '';
$article->content = '';
$article->picture = '';
$article->pubdate = date('Y-m-d');
return $article;
}
I fixed the problem by creating a new method array_me() in the model and calling it in the controller.
NEW METHOD IN MY_MODEL
public function array_me($fields) {
$uploadData = $this->upload->data();
$picture = $uploadData['file_name'];
$data = array();
foreach ($fields as $field) {
$data[$field] = $this->input->post($field);
$data['category_id'] = $this->input->post('category');
$data['picture'] = $picture;
}
return $data;
}
EDITED CONTROLLER
public function edit($post_id = NULL) {
// Fetch all articles or set a new one
if ($post_id) {
$this->data['article'] = $this->article_m->get($post_id);
count($this->data['article']) || $this->data['errors'][] = 'article could not be found';
}
else {
$this->data['article'] = $this->article_m->get_new();
}
// Set up the form
$rules = $this->article_m->rules;
$this->form_validation->set_rules($rules);
if ($this->input->post('userSubmit')) {
//check if user uploads picture
if (!empty($_FILES['picture']['name'])) {
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'jpg|png|gif|jpeg';
$config['file_name'] = $_FILES['picture']['name'];
//load upload library and initialize configuration
$this->upload->initialize($config);
if ($this->upload->do_upload('picture')) {
$uploadData = $this->upload->data();
$picture = $uploadData['file_name'];
} else {
$picture = '';
}
} else {
$picture = '';
}
// prepare array of posts data
$data = $this->article_m->array_me(array(
'title',
'slug',
'content',
'category_id',
'picture',
'pubdate'
));
$insertPosts = $this->article_m->save($data, $post_id);
redirect('admin/article');
//storing insertion status message
if ($insertPosts) {
$this->session->set_flashdata('success_msg', 'Post has been added Successfully.');
} else {
$this->session->set_flashdata('error_msg', 'error occured while trying upload, please try again.');
}
}
// Load view
$this->data['subview'] = 'admin/article/edit';
$this->load->view('admin/components/page_head', $this->data);
$this->load->view('admin/_layout_main', $this->data);
$this->load->view('admin/components/page_tail');
}

Convert uploaded pdf file to jpg in codeigniter

I am currently beginning to learn CodeIgniter. There is this site that I've been working on.
In this site, users can upload PDF files but they are only allowed to view their uploaded files in JPG format. The question is, how can I convert the PDF file into JPG on the time of upload and store JPG format instead of PDF.
here is the code of my CONTROLLER
public function upload()
{
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
$data['username'] = $session_data['username'];
$data['permission'] = $session_data['permission'];
if($data['permission']=='Super Admin' || $data['permission']=='Admin'){
$this->load->view('header');
$this->load->view('upload_form', array('error' => ' ' ));
}
}
else
{
redirect('login', 'refresh');
}
}
function do_upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'pdf';
$config['max_size'] = '10000';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('header');
$this->load->view('upload_form', array('error' => ' ' ));
}
else
{
$data = array('upload_data' => $this->upload->data());
$upload_data = $this->upload->data();
$session_data = $this->session->userdata('logged_in');
$first = $session_data['firstname'];
$last = $session_data['lastname'];
$dept = $session_data['department'];
$uploader = $first." ".$last;
$name = $upload_data['file_name'];
$path = $upload_data['file_path'];
$this->db->query("INSERT INTO tbl_uploaded
(`uploaded_id`, `name`, `path`,`department`,`uploader`)
VALUES ('','".$name."',
'". $path."','".$dept."','".$uploader."')");
redirect('csfi','refresh');
}
}
I've already read about Imagick but I don't know how to use it in CodeIgniter. Can you give me some tutorials and examples or a much easier way to convert PDF to JPG in CodeIgniter?
Thank you in advance guys.
$config = array();
$config['allowed_types'] = 'pdf';
$config['overwrite'] = TRUE;
$config['remove_spaces'] = TRUE;
$this->load->library('upload', $config);
// Image manipulation library
$this->load->library('image_lib');
foreach ($notes['name'] as $key => $note)
{
$_FILES['notes']['name'] = $notes['name'][$key];
$_FILES['notes']['type'] = $notes['type'][$key];
$_FILES['notes']['tmp_name'] = $notes['tmp_name'][$key];
$_FILES['notes']['error'] = $notes['error'][$key];
$_FILES['notes']['size'] = $notes['size'][$key];
$extension = pathinfo($_FILES['notes']['name'], PATHINFO_EXTENSION);
$unique_no = uniqid(rand(), true);
$filename[$key] = $unique_no.'.'.$extension; // with ex
$filename2[$key] = $unique_no; // without ex
$target_path = "notes_files/";
if (!is_dir($target_path))
{
mkdir('./'.$target_path, 0777, true);
}
$config['file_name'] = $filename[$key];
$config['upload_path'] = './'.$target_path;
$this->upload->initialize($config);
if (! $this->upload->do_upload('notes'))
{
return array('error' => $this->upload->display_errors());
}
// converting pdf to images with imagick
$im = new Imagick();
$im->setResolution(160,220);
$ig = 0;
while(true)
{
try {
$im->readimage($config['upload_path'].$config['file_name']."[$ig]");
} catch (Exception $e) {
$ig = -1;
}
if($ig === -1) break;
$im->setImageBackgroundColor('white');
$im->setImageAlphaChannel(imagick::ALPHACHANNEL_REMOVE);
$im->mergeImageLayers(imagick::LAYERMETHOD_FLATTEN);
$im->setImageFormat('jpg');
$image_name = $filename2[$key]."_$ig".'.jpg';
$imageprops = $im->getImageGeometry();
$im->writeImage($config['upload_path'] .$image_name);
$im->clear();
$im->destroy();
// change file permission for file manipulation
chmod($config['upload_path'].$image_name, 0777); // CHMOD file
// add watermark to image
$img_manip = array();
$img_manip = array(
'image_library' => 'gd2',
'wm_type' => 'overlay',
'wm_overlay_path' => FCPATH . '/uploads/institutes/'.$institute_logo, // path to watermark image
'wm_x_transp' => '10',
'wm_y_transp' => '10',
'wm_opacity' => '10',
'wm_vrt_alignment' => 'middle',
'wm_hor_alignment' => 'center',
'source_image' => $config['upload_path'].$image_name
);
$this->image_lib->initialize($img_manip);
$this->image_lib->watermark();
ImageJPEG(ImageCreateFromString(file_get_contents($config['upload_path'].$image_name)), $config['upload_path'].$image_name, );
$ig++;
}
// unlink the original pdf file
chmod($config['upload_path'].$config['file_name'], 0777); // CHMOD file
unlink($config['upload_path'].$config['file_name']); // remove file
}
// echo '<p>Success</p>';exit;
die(json_encode(array(
'data' => 'Success',
'status' => 'success'
)));
Try this, you can upload and convert multiple files using this.

Active Record insert query to save image in mysql database

Hello I want to save the image to the database.. I written some code but it is not working fine. my code for controller is
function UploadImageView()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '2048';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
$imgdata['file']=$_FILES;
$this->load->model('Users');
/*$response=$this->Users->Image_upload();
header('Content-type: application/json');
echo json_encode($response);
*/
foreach($_FILES as $key => $value)
{
$this->upload->initialize($config);
if ( !$this->upload->do_upload($key))
{
//PARSE ERRORS
$error = array('error' => $this->upload->display_errors());
//var_dump($error);
$msg = $this->upload->display_errors('<p>', '</p>');
echo 'errore: '.$msg;
}
else
{
$this->load->model('Users');
$this->Users->Image_upload($key);
}
}
}
and my code for the model is as follows.
function Image_upload($value)
{
$this->filedata=$value;
$handle = fopen($this->filedata,"rb");
$img =fread($handle, filesize('$filedata'));
fclose($handle);
$img = base64_encode($img);
$data=array(
'image'=>$img
);
$flag=$this->db->insert('testimage',$data);
if($flag)
{
$this->db->where('image', $this->filedata);
$query = $this->db->get('testimage');
if ($query->num_rows() == 0)
{
$response['status'] = false;
$response['userId'] = -1;
$response['message'] = "Upload Failed!";
}
else
{
$result = $query->result();
$response['status'] = true;
$response['file'] = $this->filedata;
$response['message'] = "Success!";
}
}
return $response;
}
It returns error that
"fopen(Imgupload): failed to open stream: No such file or directory"
and
Message: filesize(): stat failed for $filedata
and
fread() expects parameter 1 to be resource, boolean given etc etc
so anybody help me to save image in my database.
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);
}
Straight from the docs.
If you notice, they are sending the upload data to the view. So send it to the model instead:
$this->Users->Image_upload($this->upload->data());
Then your data is available in the array as is also explained in the docs:
$this->upload->data()
This is a helper function that returns an array containing all of the
data related to the file you uploaded. Here is the array prototype:
Array
(
[file_name] => mypic.jpg
[file_type] => image/jpeg
[file_path] => /path/to/your/upload/
[full_path] => /path/to/your/upload/jpg.jpg
[raw_name] => mypic
[orig_name] => mypic.jpg
[client_name] => mypic.jpg
[file_ext] => .jpg
[file_size] => 22.2
[is_image] => 1
[image_width] => 800
[image_height] => 600
[image_type] => jpeg
[image_size_str] => width="800" height="200"
)
So you can access the data in the model like so:
function Image_upload($data)
{
$handle = fopen($data['full_path'],'rb');
...

Resources