While attempting to upload from my Ionic App to the Codeigniter Rest Server, I encountered an issue where the image could not be previewed after it was opened. To guide me through the uploading process from the app's end, I followed this tutorial:
This is the code snippet from my Ionic App:
img = { "data":"", "user_id":"" };
getPhoto() {
let options = {
maximumImagesCount: 1
};
this.imagePicker.getPictures(options).then((results)=>{
for(let i=0; i < results.length; i++){
this.imgPreview = results[i];
this.base64.encodeFile(results[i]).then((base64File: string) => {
this.img.data = base64File;
this.status = true;
}, (err) => {
console.log(err);
});
}
});
}
// Function to submit the data to rest api
UploadImages(){
this.restProvider.postAction('my-rest-api-url', this.img).then((data)=>{
this.msg = JSON.stringify(data['img']);
this.restProvider.triggerToastMsg('Images uploaded to gallery.');
});
}
And this is the corresponding function on my Rest Server in Codeigniter:
function uploadImage_post(){
$postdata = file_get_contents("php://input");
$data = json_decode($postdata);
if(!empty($data)){
$img = $data->data;
$imgStr = substr($img, strpos($img, "base64,") + 7);
$imgData = base64_decode($imgStr);
$imgName = uniqid().'.jpg';
$imgData = array(
'author_id' => $data->user_id,
'file_src' => $imgName,
);
$this->Gallery_model->createMyGallery($imgData);
$root = dirname($_SERVER['DOCUMENT_ROOT']);
$dir = $root.'/my-dir-goes-here';
file_put_contents($dir.$imgName, $imgData);
$this->response([
'http_status_code' => REST_Controller::HTTP_OK,
'status' => true,
'statusMsg' => 'OK'
], REST_Controller::HTTP_OK);
}
}
Upon examining the API side, when accessing $data->data
, it displays the encoded base64 data format which looks like
data:image/*;charset=utf-8;base64,/9j/4AAQSkZjRgA....................
To eliminate the prefix
data:image/*;charset=utf-8;base64,
, I utilized the substr()
method to extract only the essential base64 data like /9j/4AAQSkZjRgA....................
. Despite successfully storing the image in my server directory, attempts to open the image result in a corrupted file message. Additionally, the image size is significantly small at only 19 bytes.