无法预览上传的图像[rest api]



我正试图从我的Ionic应用程序上传到codeigniter Rest Server,但打开它时无法预览图像。我参考本教程从应用程序端进行上传https://www.djamware.com/post/5ae9c9ca80aca714d19d5b9f/ionic-3-angular-5-and-cordova-base64-image-upload-example

这是我在Ionic应用程序中的代码:

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.');
});
}

来自Codeigniter端的Rest服务器:

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);
}
}

从api端可以看到,$data->data将产生编码的base64,类似于data:image/*;charset=utf-8;base64,/9j/4AAQSkZjRgA....................

因此,为了去除data:image/*;charset=utf-8;base64,,我使用substr()来获得/9j/4AAQSkZjRgA....................之后的数据,然后只有我将其解码回来。我设法把它上传到我的服务器目录,但当我试图打开图像时,它没有打开。它会看起来像图像损坏了。图像文件大小也很小,19字节

仔细查看您的休息服务器端。您已经两次分配$imgData值,这是将解码的base64的值替换为数组值。这就是为什么file_put_contents($dir.$imgName, $imgData);行上的代码无法获取要保存的图像的原因。

您应该按照以下顺序放置代码:

$img = $data->data;
$imgStr = substr($img, strpos($img, "base64,") + 7);
$imgData = base64_decode($imgStr);
$imgName = uniqid().'.jpg';
$root = dirname($_SERVER['DOCUMENT_ROOT']);
$dir = $root.'/my-dir-goes-here';
file_put_contents($dir.$imgName, $imgData);
$imgData = array(
'author_id'   => $data->user_id,
'file_src'    => $imgName,
);
$this->Gallery_model->createMyGallery($imgData);

最新更新