Upload File from Rest client to codeigniter - php

I know it could be a duplicate but i need a bit more help in that.
I have started working on making api for an android application in codeigniter. And currently working on making api for uploading an image.. I am using https://github.com/chriskacerguis/codeigniter-restserver
using postman to upload images to test my API but
but i am getting something like
'------WebKitFormBoundaryXkKFa0QV2XVs0EoK
Content-Disposition:_form-data;_name' => string '"filesss"; filename="17264394_1739947152983817_1705887364349350305_n.jpg"
Content-Type: image/jpeg
�����JFIF����������Photoshop 3.0�8BIM������g�Vnlfejt43YHm4REx3e4k(�bFBMD01000abe0300002f19000082320000643300004b3400002f4d0000c46f0000d3750000b8780000b07b000096cd0000��ICC_PROFILE���lcms��mntrRGB XYZ
Now can any one help me how to be able to save the image on my server
below is my code
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
require_once APPPATH . './libraries/REST_Controller.php';
use Restserver\Libraries\REST_Controller;
class Update_image extends REST_Controller{
function __construct(){
parent::__construct();
$models[] = 'Quiz_model';
$models[] = 'Users_model';
$this->load->model($models);
$libs[] = 'form_validation';
$libs[] = 'image_lib';
$libs[] = 'email';
//$libs[] = 'rest';
$this->load->library($libs);
$helpers[] = 'file';
$helpers[] = 'security';
$helpers[] = 'url';
$helpers[] = 'string';
$this->load->helper($helpers);
}
function index_post(){
$users_id = $this->input->post('users_id');
$users_id = 6;
$config['upload_path'] = './public/user_images/';
$config['allowed_types'] = 'jpg|png';
$config['max_size'] = ; // for 5mb file
$config['max_width'] = 5000;
$config['max_height'] = 5000;
$this->load->library('upload', $config);
if(!$this->upload->do_upload('users_image')){
$error = array('error' => $this->upload->display_errors('<span>','<span>'));
$data['msg'] = error('Please Fix the errors below');
$data['file_upload_error'] = formErrorParse($this->upload->display_errors());
$this->form_validation->set_message('quiz_image', implode('<br/>', $error));
$response['status'] = 0;
$response['msg'] = strip_tags($this->upload->display_errors());
}else{
$uploadStat = $this->upload->data();
$img_config['image_library'] = 'gd2';
$img_config['source_image'] = './public/uploads/user_images/'.$uploadStat['file_name'];
$img_config['new_image'] = './public/uploads/user_images/thumbnail/'.$uploadStat['file_name'];
//$img_config['create_thumb'] = TRUE;
$img_config['maintain_ratio'] = TRUE;
$img_config['width'] = 150;
$img_config['height'] = 150;
$this->image_lib->clear();
$this->image_lib->initialize($img_config);
$this->image_lib->resize();
$updates['users_images'] = $uploadStat['file_name'];
$cond['users_id'] = $users_id;
$this->db->update('users', $updates, $cond);
$response['status'] = 1;
$response['msg'] = 'Image Uploaded';
}
$this->response($response, 200);
}
}

I had exactly same problem as you.
But solved after removing Content-Type from headers in postman.
Then you'll get data in $_FILES.

Make sure your php version is 5.6 or above,i had the same problem and solved it by switching to php version 7.

Related

Use Google Cloud Vision in Codeigniter, Cannot Find Class ImageAnnotatorClient

I want to implement the google cloud vision textDetection using a google cloud vision.
I have install the composer from google cloud vision to the thirdparty vendor in codeignier.
What my setup in construct is :
include APPPATH . 'third_party/vendor/autoload.php';
require_once APPPATH.'third_party/vendor/google/cloud-vision/src/V1/ImageAnnotatorClient.php';
and my function to call the OCR is :
function upload_ocr_image()
{
if (count($_FILES) === 0) { echo 'no image received from unity'; }
$phone_code = $this->input->post('phone_code', true);
$phone_number = $this->input->post('phone_number', true);
$allowedType = array(IMAGETYPE_GIF,IMAGETYPE_JPEG,IMAGETYPE_PNG);
$imgType = exif_imagetype($_FILES['ocr_image']['tmp_name']);
if(!in_array($imgType,$allowedType))
{
echo "Images Type Error. Images Type Only : GIF , JPEG, PNG";
exit;
}
else
{
//upload original size front end slider
$config['upload_path'] = './assets/ocr_image/';
$config['allowed_types'] = '*';
$config['file_name'] = $phone_code.$phone_number.".jpg";
$config['overwrite'] = TRUE;
$config['max_size'] = '8096';
$config['max_width'] = '8000';
$config['max_height'] = '8000';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if(!$this->upload->do_upload("ocr_image"))
{
echo "Maximum File Size Only 2 Mb Or Max Width = 2000 , Height = 2000";
exit;
}
else
{
$img_data = $this->upload->data();
// Authenticating with a keyfile path.
$imageAnnotator = new ImageAnnotatorClient([
'credentials' => base_url().'assets/google_cloud_vision/keyfile.json'
]);
# annotate the image
$response = $imageAnnotator->textDetection($img_data['full_path']);
$texts = $response->getTextAnnotations();
printf('%d texts found:' . PHP_EOL, count($texts));
foreach ($texts as $text) {
print($text->getDescription() . PHP_EOL);
# get bounds
$vertices = $text->getBoundingPoly()->getVertices();
$bounds = [];
foreach ($vertices as $vertex) {
$bounds[] = sprintf('(%d,%d)', $vertex->getX(), $vertex->getY());
}
print('Bounds: ' . join(', ',$bounds) . PHP_EOL);
}
$imageAnnotator->close();
}
}
}
But before process the text detection i have run into an error :
Fatal error: Class 'ImageAnnotatorClient' not found
Which is this line :
$imageAnnotator = new ImageAnnotatorClient([
What could possible cause the error ? From the construct above i already include or require_once the Path to the Class.
Is there something that i have missed in here ?
Thank You
This is the answer.
Check this post : Namespace in PHP CodeIgniter Framework
Just add the code to detect the namespace in the bottom of the config.php

How to delete old file from the folder while updating?

I want to delete the old file from the folder ie, if I update an image the old one remains as it is in the folder and a new one is get uploaded.
Here updating is done fine but after frequent updating number of files is increasing .
This is the code for selecting the content from the database and also for updating
public function select_testimonials($id)
{
$this->session->set_userdata('id',$id );
$query = $this->cl_testimonials_model->select($id);
$data1['selectdata'] = $query->result();
// $this->index();
$query = $this->db->get("cl_testimonials");
$data1['records'] = $query->result();
$this->load->view('admin/testimonials/testimonials_edit',$data1);
}
public function update_testimonials()
{
$id = $this->input->post("id");
if ($this->input->post('submit')=="update")
{
if(!empty($_FILES['picture']['name']))
{
$config['upload_path'] = 'uploads/images/testimonials';
$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);
if($this->upload->do_upload('picture'))
{
$uploadData = $this->upload->data();
$picture = $uploadData['file_name'];
}
}
//Prepare array of user data
$data = array('name' => $this->input->post('name'),'content' => $this->input->post('content'),'picture' => $picture);
//Pass user data to model
$insertUserData = $this->cl_testimonials_model->update($id,$data);
}
//Storing insertion status message.
if(isset($insertUserData))
{
$data['message']="* testimonials updated successfully.";
}
else
{
$data['message']="* Some problems occured, please try again.";
}
$query = $this->db->get("cl_testimonials");
$data['records'] = $query->result();
$this->load->view('admin/testimonials/testimonials_listing',$data);
}
Fetch Existing testimonial picture path by id, update, then use unlink('old file path')
More here : Here
Use the unlink(); function in php. it is applicable also in Codeigniter.
unlink("target path/".$file name);

how can i check the value of a variable from a controller in codeigniter

I am doing an upload image file in CodeIgniter. I want to trace out the image in my code and update my database path with it. I want to print the $image_path variable in the code below where it was located in my controller.
How can I print the $image_path variable to display or check its value inside the controller or maybe echo it out ?
Here it is:
<?php
public function upload_file()
{
$status = "";
$msg = "";
$file_element_name = 'userfile';
if ($status != "error") {
$config['upload_path'] = './assets/upimages/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 1024 * 8;
$config['encrypt_name'] = FALSE;
$this->load->library('upload', $config);
if (!$this->upload->do_upload($file_element_name))
{
$status = 'error';
$msg = $this->upload->display_errors('', '');
}
else
{
$data = $this->upload->data();
$image_path = $data['full_path'];
if(file_exists($image_path))
{
$status = "success";
$msg = "File successfully uploaded";
}
else
{
$status = "error";
$msg = "Something went wrong when saving the file, please try again.";
}
}
#unlink($_FILES[$file_element_name]);
}
echo json_encode(array('status' => $status, 'msg' => $msg));
}
?>
If I understand the question your asking then you want to view the contents of the $image_path variable.
If all you want is to check this then you could pass it back to the view with the json array ('image_path' => $image_path).
The other option is to var_dump($image_path) however to view this you would need to inspect the post data response on the browser and it may also stop the json from working while you are using the var_dump().
Blinky
try echo $image_path; or print_r($image_path)

how to submit file using jquery to codeigniter controller

May I ask for your help guys!
I am trying to upload a file and passing all the data to codeigniter controller using jquery.
my view file:
<div class="form-group">
<label class="col-md-4 control-label">Item Image</label>
<div class="col-md-8">
<input class="form-control" type="file" placeholder="" id="itemImage" name="itemImage" data-parsley-required="true" />
</div>
</div>
<button type="button" onclick="add_item();">Sumit</button>
<script>
function add_item(){
$.post('<?php echo site_url('admin_newitem/add_item'); ?>',
{
itemId : $('#itemId').val(),
itemImage : $('#itemImage').val()
},
function(data){
if(data.result=='SUCCESS'){
$('#itemId').val('');
$('#itemImage').val('');
//show success
}else{
//show error
}
},'json'
);
}
</script>
My controller:
function add_item(){
$this->output->set_status_header(200);
$this->output->set_header('Content-Type: application/json');
$itemId = $this->input->post('itemId');
$itemImage = $this->input->post('itemImage');;
$config['upload_path'] = realpath(APPPATH.'../assets_main/img/item/');
$config['allowed_types'] = 'jpg|jpeg';
$config['max_size'] = '100';
$config['max_width'] = '200';
$config['max_height'] = '200';
$file_name = $config['file_name'] = md5(uniqid(mt_rand()));
$config['remove_spaces'] = TRUE;
$this->load->library('upload', $config);
if(!$itemImage){
$jdata['result'] = "FAILED";
$jdata['message'] = "upload error.";
$jdata['field'] = "itemImage";
echo json_encode($jdata);
exit();
}
$data = array('upload_data' => $this->upload->data());
$jdata['message'] = "Thank you for purchasing our item!";
$jdata['result'] = "SUCCESS";
echo json_encode($jdata);
exit();
}
I was able to get the ItemId, and ItemImage but when I check the folder where the image is suppose to be located, it's not there. I think I fail to capture the real file, so, is there a way for me to get this done?
As you suggest, I believe that you are forgetting to actually do the upload, the code igniter documentation might help:
http://www.codeigniter.com/user_guide/libraries/file_uploading.html
With this correctly implemented, I think your code should look something similar to:
function add_item(){
$this->output->set_status_header(200);
$this->output->set_header('Content-Type: application/json');
$itemId = $this->input->post('itemId');
$itemImage = $this->input->post('itemImage');;
$config['upload_path'] = realpath(APPPATH.'../assets_main/img/item/');
$config['allowed_types'] = 'jpg|jpeg';
$config['max_size'] = '100';
$config['max_width'] = '200';
$config['max_height'] = '200';
$file_name = $config['file_name'] = md5(uniqid(mt_rand()));
$config['remove_spaces'] = TRUE;
$this->load->library('upload', $config);
//THE MISSING LINE
if($this->upload->do_upload()){
//THE FILE HAS NOW BEEN UPLOADED
$data = array('upload_data' => $this->upload->data());
$jdata['message'] = "Thank you for purchasing our item!";
$jdata['result'] = "SUCCESS";
echo json_encode($jdata);
exit();
}else{
//NO FILE UPLOADED
$jdata['result'] = "FAILED";
$jdata['message'] = "upload error.";
$jdata['field'] = "itemImage";
echo json_encode($jdata);
exit();
}
}
My initial thinking, having used CI and tried to do this same thing, is that you can't do file uploads via AJAX without a special plugin such as this:
http://malsup.com/jquery/form/
Specifically, this file upload portion:
http://malsup.com/jquery/form/#file-upload
Simply trying to send a post with the val of a file input will not work, I don't believe - though maybe more modern browsers are able to handle that now.

Codeigniter, uploading multiple files with same name

I have an upload form that allows me to add as many files as needed. However when I start trying to upload the files I get an error.
Controller
$this->load->library('upload');
$error = "";
$file = "";
$this->total_count_of_files = count($_FILES['user_certificates']['name']);
print_r($_FILES['user_certificates']['name']);
for($i=0; $i<$this->total_count_of_files; $i++)
{
$_FILES['user_certificates']['name'] = $_FILES['user_certificates']['name'][$i];
$_FILES['user_certificates']['type'] = $_FILES['user_certificates']['type'][$i];
$_FILES['user_certificates']['tmp_name'] = $_FILES['user_certificates']['tmp_name'][$i];
$_FILES['user_certificates']['error'] = $_FILES['user_certificates']['error'][$i];
$_FILES['user_certificates']['size'] = $_FILES['user_certificates']['size'][$i];
$config['encrypt_name'] = TRUE;
$config['file_name'] = $_FILES['user_certificates']['name'];
$config['upload_path'] = './certificate_files/';
$config['allowed_types'] = 'txt|pdf|doc|docx';
$config['max_size'] = 0;
$this->upload->initialize($config);
if (!$this->upload->do_upload())
{
$status = 'error';
$msg = $this->upload->display_errors();
}
else
{
$data = $this->upload->data();
$file = $data['raw_name'] . $data['file_ext'];
}
if($file)
{
$status = "success";
$msg = "Image successfully uploaded";
}
else
{
$status = "error";
$msg = "Something went wrong when saving the image, please try again.";
}
}
echo json_encode(array('status' => $status, 'msg' => $msg));
exit();
The print_r($_FILES['user_certificates']['name'])) shows me the files I have added:
Array ( [0] => license.txt [1] => license.txt )
I am totally stuck on how to get the upload to work. Any ideas?
Cheers in advance!
EDIT
If I change this:
if (!$this->upload->do_upload())
to this:
if (!$this->upload->do_upload('user_certificates'))
it works, but only for one file, it doesn't seem to loop round again for some reason
Your loops seems to be incorrect.
...
$_FILES['user_certificates']['name'] = $_FILES['user_certificates']['name'][$i];
...
these lines overwrite the original $_FILES array, so after completion of first loop, it will not find anything else in the loop because it got overwritten.
Instead you may first store the $_FILES array to a local variable and loop through it to upload one by one.

Categories