我正在尝试从Ionic App上传到codeigniter Rest Server,但是打开图像时无法预览。我指的是从应用程序侧https://www.djamware.com/post/5ae9c9ca80aca714d19d5b9f/ionic-3-angular-5-and-cordova-base64-image-upload-example
进行上传的本教程这是我来自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.');
});
}
从我在Codeigniter端的Rest Server中:
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个字节
答案 0 :(得分:1)
仔细查看其余服务器端。您已经两次分配了$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);