I'm trying to do uploading from my Ionic App to the codeigniter Rest Server but the image cannot be previewed when I open it. I'm referring to this tutorial to do the uploading from the app side https://www.djamware.com/post/5ae9c9ca80aca714d19d5b9f/ionic-3-angular-5-and-cordova-base64-image-upload-example
Here is my code from 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.');
});
}
From my Rest Server in Codeigniter side :
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);
}
}
From what you can see on the api side, the $data->data will resulting the encoded base64 which is something like data:image/*;charset=utf-8;base64,/9j/4AAQSkZjRgA....................
So, in order to remove the data:image/*;charset=utf-8;base64, I use the substr() to get the data after it /9j/4AAQSkZjRgA.................... then only I decode it back. I manage to upload it to my server directory but when I tried to open the image, it doesn't open it. It will appear something like image corrupted. The image filesize also just small which is 19 bytes
Look closely to your rest server side. You've been assigning
$imgDatavalue twice which is replacing the value of the decoded base64 to an array value. That is why your code on the linefile_put_contents($dir.$imgName, $imgData);unable to get the image that you're trying to save.You should place your code in this order :