Problem:
When try to store an image in MySql database field (BLOB) through codeigniter service, the image is not enabled in mysql. (I know is not a good practice but requirement). When is upload the image through mysl admin, image its ok.
How do i test?
I use postman with several text fields and one "file" field where i take the image to be stored in database.
Postman
Results of test:
All "text" fields are stored in database, the "file" field is uploaded to a directory as expected but the bynary data is not stored in database in field "foto"
Results in MySql
Code in Codeigneter:
public function CrearCliente(){
$user = $this->input->post('user');
$nombre = $this->input->post('nombre');
$apellido = $this->input->post('apellido');
$rut = $this->input->post('rut');
$correo = $this->input->post('correo');
$id_pais = $this->input->post('id_pais');
$fecha = $this->input->post('creacion');
$password = $this->input->post('password');
$presentacion = $this->input->post('presentacion');
$telefono = $this->input->post('telefono');
$long = 0;
$lat = 0;
$res="null";
$this->load->library('form_validation');
$mimetypes = array("image/jpeg", "image/pjpeg", "image/gif", "image/png");
$foto = $_FILES['foto']['name'];
$tamanio = $_FILES['foto']["size"];
$archivo = $_FILES['foto']['tmp_name'];
$type = $_FILES['foto']['type'];
$imagen = fopen($archivo, 'rb');
$contenido2 = fread($imagen, $tamanio);
$contenido=file_get_contents($archivo,TRUE);
$contenido3 = $this->db->escape_str($contenido);
fclose($imagen);
if(!in_array($type, $mimetypes))
die("El archivo que subiste no es una imagen válida");
$config['upload_path'] = './imagenes/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '5000000';
$config['quality'] = '90%';
$config['overwrite'] = TRUE;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$config['file_name'] = $foto;
$this->load->library('upload', $config);
if (!$this->upload->do_upload('foto')) {
$error = array('error' => $this->upload->display_errors());
$data['uploadError'] = $this->upload->display_errors();
die('error');
}
else{
$data = array('upload_data' => $this->upload->data());
}
$this->load->model('Usuario');
$res = $this->Usuario->InsertUsuario($contenido3,$user, $nombre, $apellido,$rut, $correo, $foto,$tamanio,$id_pais,$fecha,$password,$presentacion,$telefono,$long,$lat); // *se le asigna una variable al modelo para guardar el contenido que retorna la bd
header('content-type: application/json'); //* se colcoa una cabezera para decir que se va a retornar un Json
echo json_encode($res);
}
function InsertUsuario($contenido,$user, $nombre, $apellido,$rut, $correo, $foto,$tamanio,$id_pais,$fecha,$password,$presentacion,$telefono,$long,$lat)
{
$hoy=getdate();
if ($foto) {
echo $contenido;
}
else{
$imagen = null;
header('content-type: application/json');
echo json_encode("./upload/error.jpg");
}
$this->db->trans_strict(TRUE);
$this->db->trans_start();
$data = array(
'user' => $user,
'nombre' => $nombre,
'apellido' => $apellido,
'id_rut' => $rut,
'correo' => $correo,
'foto' => $contenido,
'id_pais' => $id_pais,
'password' => $password,
'presentacion' => $presentacion,
'telefono' => $telefono,
'creacion' => $fecha,
'long' => $long,
'lat' => $lat
);
$this->db->insert('wm_clientes',$data);
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE)
{
return $res='ERROR';
}
else
{
return $res='OK';
}
}
Question: Why the data related to image (jpg) file is not storing in database? Check image. I tried a lot of things but seen to be more difficult i expected. Need help gurus!
strong text
Try this:
public function CrearCliente() {
$user = $this->input->post('user');
$nombre = $this->input->post('nombre');
$apellido = $this->input->post('apellido');
$rut = $this->input->post('rut');
$correo = $this->input->post('correo');
$id_pais = $this->input->post('id_pais');
$fecha = $this->input->post('creacion');
$password = $this->input->post('password');
$presentacion = $this->input->post('presentacion');
$telefono = $this->input->post('telefono');
$long = 0;
$lat = 0;
$res = "null";
$this->load->library('form_validation');
$mimetypes = array("image/jpeg", "image/pjpeg", "image/gif", "image/png");
$foto = $_FILES['foto']['name'];
$tamanio = $_FILES['foto']["size"];
$archivo = $_FILES['foto']['tmp_name'];
$type = $_FILES['foto']['type'];
//$imagen = fopen($archivo, 'rb');
//$contenido2 = fread($imagen, $tamanio);
//fclose($imagen);
if (!in_array($type, $mimetypes)) {
// ci upload checks mimes for you
show_error("El archivo que subiste no es una imagen válida");
}
$config['upload_path'] = './imagenes/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '5000000';
$config['quality'] = '90%';
$config['overwrite'] = TRUE;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$config['file_name'] = $foto;
$this->load->library('upload', $config);
if (!$this->upload->do_upload('foto')) {
//$error = array('error' => $this->upload->display_errors());
//$data['uploadError'] = $this->upload->display_errors();
show_error($this->upload->display_errors());
}
$contenido = file_get_contents($this->upload->data('full_path'));
$contenido3 = $this->db->escape_str($contenido);
$this->load->model('Usuario');
$res = $this->Usuario->InsertUsuario($contenido3, $user, $nombre, $apellido, $rut, $correo, $foto, $tamanio, $id_pais, $fecha, $password, $presentacion, $telefono, $long, $lat); // *se le asigna una variable al modelo para guardar el contenido que retorna la bd
header('content-type: application/json'); //* se colcoa una cabezera para decir que se va a retornar un Json
echo json_encode($res);
}
function InsertUsuario($contenido, $user, $nombre, $apellido, $rut, $correo, $foto, $tamanio, $id_pais, $fecha, $password, $presentacion, $telefono, $long, $lat) {
$hoy = getdate();
if ($foto) {
echo $contenido;
} else {
$imagen = null;
header('content-type: application/json');
echo json_encode("./upload/error.jpg"); // this doesn't seem valid, also you should probably exit
}
// no need for transaction when only running 1 query
$this->db->trans_strict(TRUE);
$this->db->trans_start();
$data = array(
'user' => $user,
'nombre' => $nombre,
'apellido' => $apellido,
'id_rut' => $rut,
'correo' => $correo,
'foto' => $contenido,
'id_pais' => $id_pais,
'password' => $password,
'presentacion' => $presentacion,
'telefono' => $telefono,
'creacion' => $fecha,
'long' => $long,
'lat' => $lat
);
$this->db->insert('wm_clientes', $data);
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE) {
return $res = 'ERROR';
} else {
return $res = 'OK';
}
}
I would also suggest sending the array of data to the insert function instead of each as a parameter - it is messy and confusing and prone to errors. I also wouldn't suggest mixing string return types with json return types as it is an inconsistent interface. Also if you are using ajax you need to use FormData or a plugin to upload a file in case you weren't.
Any easy way around this would be to just store the image on your server (which you are doing already with your code) and then save the image name to your database as a varchar.
$config['upload_path'] = './imagenes/';
Above is the code that is uploading it to your server. It goes to that path on your server using the upload library provided by codeigniter.
You can now query your database for the image name, rather than the actual image, and use that in your view in an image tag. This will pull the image from the server.
If you have any questions about this method let me know.
Related
my model
public function saveProduct(
$name,
$cat_id,
$user_id,
$description,
$status
) {
$post_image = '';
if (array_key_exists('post_image', $_FILES)) {
$config = [];
$config['upload_path'] = './assets/uploads/products';
$config['allowed_types'] = 'gif|svg|jpg|png|jpeg';
$config['max_size'] = '2048';
$config['overwrite'] = TRUE;
$config['remove_spaces'] = TRUE;
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('post_image')) {
echo $this->upload->display_errors();
} else {
$post_image = $_FILES['post_image']['name'];
}
}
$data = [
'name' => $name,
'user_id' => $user_id,
'cat_id' => $cat_id,
'description' => $description,
'status' => 'active'
];
if ($post_image) {
$data['post_image'] = $post_image;
}
$this->db->insert('p0_products', $data);
return true;
}
it is changing file name to encryption in folder but in mysql i'am getting file name same as old name with unchanged on non-encrypted format
It's because you're taking from $_FILES veriable. You should take from
$this->upload->data()
So how?
$fileData = $this->upload->data();
This will return
file_name
file_type
file_path
etc.
$fileName = $fileData['file_name']
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.
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.
I am trying to upload multiple images at once but this code contain error and a error message is showing that Undefined index: photo1A. So help me to fix it.
function add_student_database(){
//echo '<pre>';print_r($_POST);print_r($_FILES);exit;
$this->load->library('upload');
if($this->input->post('stu_class')=='first' && $this->input->post('section')=='A')
{
$data = $this->input->post('student1A');
$img_data = $_FILES['photo1A'];
// echo '<pre>';print_r($_FILES);exit;
$count = count($_FILES['photo1A']);
$config['upload_path'] = './upload/';
$config['allowed_types'] = 'jpg|png|gif';
$config['max_size'] = '100000';
$config['max_width'] = '2000';
$config['max_height'] = '2000';
$this->load->library('upload', $config);
for($i=0;$i<$count;$i++)
{
$_FILES['photo1A']['name'] = $img_data['photo1A']['name'][$i];
$_FILES['photo1A']['type'] = $img_data['photo1A']['type'][$i];
$_FILES['photo1A']['tmp_name'] = $img_data['photo1A']['tmp_name'][$i];
$_FILES['photo1A']['error'] = $img_data['photo1A']['error'][$i];
$_FILES['photo1A']['size'] = $img_data['photo1A']['size'][$i];
$this->upload->initialize($config);
$this->upload->do_upload('photo1A');
}
$section = "A";
$stu_class = "class1";
}
elseif($this->input->post('stu_class')=='first' && $this->input->post('section')=='B')
{
$data = $this->input->post('student1B');
$section = "B";
$stu_class = "class1";
}
elseif($this->input->post('stu_class')=='second' && $this->input->post('section')=='A')
{
$data = $this->input->post('student2A');
$section = "A";
$stu_class = "class2";
}
elseif($this->input->post('stu_class')=='second' && $this->input->post('section')=='B')
{
$data = $this->input->post('student2B');
$section = "B";
$stu_class = "class2";
}
$this->marksheet_data->get_data($data, $section, $stu_class);
}
$message="";
$error=0;
$data1 = $this->input->post('data1');
$data2 = $this->input->post('data2');
$data3 = $this->input->post('data3');
$data.. = $this->input->post('data..');
$datan = $this->input->post('datan');
if($error==0)
{
$newdata = array(
'colName1_of_table' => $data1,
'colName2_of_table' => $data1,
'colName..._of_table'=>$data..,
'colNamen_of_table'=>$datan
);
$insert = $this->db->insert('tblName', $newdata);
$lastid=$this->db->insert_id();
if($insert)
{
//.............image upload.......................................//
$config['upload_path'] = PHYSICAL_PATH.'design/front/';
//$config['allowed_types'] = 'gif|png|jpeg|jpg';
$config['allowed_types'] = '*'; //allow all type of file with any extension
$config['max_size'] = 1024 * 8;
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
$status = "";
$msg = "";
$userpicture='';
if(!empty($_FILES["inputTAGnameOFfirstImage"]["name"]))
{
$file_element_name = 'inputTAGnameOFfirstImage';
if (!$this->upload->do_upload($file_element_name))
{
$status = 'error';
$msg = $this->upload->display_errors('', '');
}
else
{
$data = $this->upload->data();
if($data)
{
$config = array(
'source_image' => $data['full_path'],
'new_image' => $config['upload_path'] . '/thumbnail/',
'maintain_ratio' => true,
'width' => 100,
'height' => 100
);
$this->load->library('image_lib', $config);
$this->image_lib->resize();
$this->image_lib->clear(); /*this is important*/
$userpicture = $data['file_name'];
}
}
$image_data=array(
'colNameofImage_to_store' => $userpicture
);
$this->db->where('id', $lastid);
$insert_image = $this->db->update('tblName',$image_data);
}
//for Next image
$config1['upload_path'] = PHYSICAL_PATH.'design/back/';
//$config1['allowed_types'] = 'gif|png|jpeg|jpg';
$config1['allowed_types'] = '*';
$config1['max_size'] = 1024 * 8;
$config1['encrypt_name'] = TRUE;
$this->load->library('upload', $config1);
$this->upload->initialize($config1);
$status = "";
$msg = "";
$userpicture1='';
if(!empty($_FILES["inputTAGnameOFsecondImage"]["name"]))
{
$file_element_name = 'inputTAGnameOFsecondImage';
if (!$this->upload->do_upload($file_element_name))
{
$status = 'error';
echo $msg = $this->upload->display_errors('', '');
}
else
{
$data1 = $this->upload->data();
if($data1)
{
$config2 = array(
'source_image' => $data1['full_path'],
'new_image' => $config1['upload_path'] . '/thumbnail/',
'maintain_ratio' => true,
'width' => 100,
'height' => 100
);
// Initialize
$this->load->library('image_lib', $config2, 'image_lib_thumb');
//$this->image_lib->resize();
$this->image_lib_thumb->resize();
$this->image_lib_thumb->clear(); /*this is important*/
$userpicture1 = $data1['file_name'];
}
}
$new_image_data=array(
'second Image _colName_inTbl' => $userpicture1
);
$this->db->where('id', $lastid);
$insert_image = $this->db->update('tblName',$new_image_data);
}
}
return $insert;
}
Hope this help you. Question are welcome. Loop according to your need as you were trying to do.
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');
...